giulio98/xlcost-single-prompt huggingface dataset:
# hosoya 's triangle | python3 program to print hosoya 's triangle of height n. ; print the hosoya triangle of height n . ; base case . ; for each row . ; for each column ; recursive steps . ; printing the solution ; 

N = 5


def printHosoya(n):
    dp = [[0 for i in range(N)]for i in range(N)]
    dp[0][0] = dp[1][0] = dp[1][1] = 1
    for i in range(2, n):
        for j in range(n):
            if (i > j):
                dp[i][j] = (dp[i - 1][j] + dp[i - 2][j])
            else:
                dp[i][j] = (dp[i - 1][j - 1] + dp[i - 2][j - 2])
    for i in range(n):
        for j in range(i + 1):
            print(dp[i][j], end=' ')
        print()


n = 5
printHosoya(n)

# Expected output:
1 
1 1 
2 1 2 
3 2 2 3 
5 3 4 3 5
# different ways to sum n using numbers greater than or equal to m | python3 program to find number of ways to which numbers that are greater than given number can be added to get sum . ; return number of ways to which numbers that are greater than given number can be added to get sum . ; filling the table . k is for numbers greater than or equal that are allowed . ; i is for sum ; initializing dp [ i ] [ k ] to number ways to get sum using numbers greater than or equal k + 1 ; if i > k ; 

import numpy as np
MAX = 100


def numberofways(n, m):
    dp = np .zeros((n + 2, n + 2))
    dp[0][n + 1] = 1
    for k in range(n, m - 1, -1):
        for i in range(n + 1):
            dp[i][k] = dp[i][k + 1]
            if (i - k >= 0):
                dp[i][k] = (dp[i][k] + dp[i - k][k])
    return dp[n][m]


if __name__ == "__main__":
    n, m = 3, 1
    print(numberofways(n, m))

# Expected output:
3.0
# entringer number | return entringer number e ( n , k ) ; base case ; base case ; recursive step ; 
def zigzag(n, k):
    if (n == 0 and k == 0):
        return 1
    if (k == 0):
        return 0
    return zigzag(n, k - 1) + zigzag(n - 1, n - k)


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

# Expected output:
5
# eulerian number | return euleriannumber a ( n , m ) ; for each row from 1 to n ; for each column from 0 to m ; if i is greater than j ; if j is 0 , then make that state as 1. ; basic recurrence relation . ; 
def eulerian(n, m):
    dp = [[0 for x in range(m + 1)]for y in range(n + 1)]
    for i in range(1, n + 1):
        for j in range(0, m + 1):
            if (i > j):
                if (j == 0):
                    dp[i][j] = 1
                else:
                    dp[i][j] = (((i - j) * dp[i - 1][j - 1]) +
                                ((j + 1) * dp[i - 1][j]))
    return dp[n][m]


n = 3
m = 1
print(eulerian(n, m))

# Expected output:
4
# delannoy number | return the nth delannoy number . ; base case ; recursive step . ; 
def dealnnoy(n, m):
    if (m == 0 or n == 0):
        return 1
    return dealnnoy(m - 1, n) + dealnnoy(m - 1, n - 1) + dealnnoy(m, n - 1)


n = 3
m = 4
print(dealnnoy(n, m))

# Expected output:
129
# delannoy number | return the nth delannoy number . ; base cases ; 
def dealnnoy(n, m):
    dp = [[0 for x in range(n + 1)]for x in range(m + 1)]
    for i in range(m):
        dp[0][i] = 1
    for i in range(1, m + 1):
        dp[i][0] = 1
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1] + dp[i][j - 1]
    return dp[m][n]


n = 3
m = 4
print(dealnnoy(n, m))

# Expected output:
129
# longest alternating ( positive and negative ) subarray starting at every index | python3 program to find longest alternating subarray starting from every index . ; fill count [ ] from end . ; print result ; 
def longestAlternating(arr, n):
    count = [None] * n
    count[n - 1] = 1
    i = n - 2
    while i >= 0:
        if (arr[i] * arr[i + 1] < 0):
            count[i] = count[i + 1] + 1
        else:
            count[i] = 1
        i = i - 1
    i = 0
    while i < n:
        print(count[i], end=" ")
        i = i + 1


a = [-5, -1, -1, 2, -2, -3]
n = len(a)
longestAlternating(a, n)

# Expected output:
1 1 3 2 1 1
# maximum value with the choice of either dividing or considering as it is | function for calculating max possible result ; compute remaining values in bottom up manner . ; 
def maxDP(n):
    res = list()
    res .append(0)
    res .append(1)
    i = 2
    while i < n + 1:
        res .append(
            max(i, (res[int(i / 2)] + res[int(i / 3)] + res[int(i / 4)] + res[int(i / 5)])))
        i = i + 1
    return res[n]


n = 60
print("MaxSum =", maxDP(n))

# Expected output:
MaxSum = 106
# maximum difference of zeros and ones in binary string | python program to find the length of substring with maximum difference of zeroes and ones in binary string . ; return true if there all 1 s ; checking each index is 0 or not . ; find the length of substring with maximum difference of zeroes and ones in binary string ; if string is over ; if the state is already calculated . ; returns length of substring which is having maximum difference of number of 0 s and number of 1 s ; if all 1 s return - 1. ; else find the length . ; 

MAX = 100


def allones(s, n):
    co = 0
    for i in s:
        co += 1 if i == '1'else 0
    return co == n


def findlength(arr, s, n, ind, st, dp):
    if ind >= n:
        return 0
    if dp[ind][st] != -1:
        return dp[ind][st]
    if not st:
        dp[ind][st] = max(
            arr[ind] +
            findlength(
                arr,
                s,
                n,
                ind +
                1,
                1,
                dp),
            (findlength(
                arr,
                s,
                n,
                ind +
                1,
                0,
                dp)))
    else:
        dp[ind][st] = max(arr[ind] + findlength(arr, s, n, ind + 1, 1, dp), 0)
    return dp[ind][st]


def maxLen(s, n):
    if allones(s, n):
        return -1
    arr = [0] * MAX
    for i in range(n):
        arr[i] = 1 if s[i] == '0'else -1
    dp = [[-1] * 3 for _ in range(MAX)]
    return findlength(arr, s, n, 0, 0, dp)


s = "11000010001"
n = 11
print(maxLen(s, n))

# Expected output:
6
# minimum jumps to reach last building in a matrix | recursive python3 program to find minimum jumps to reach last building from first . ; returns minimum jump path from ( 0 , 0 ) to ( m , n ) in height [ r ] [ c ] ; base case ; find minimum jumps if we go through diagonal ; find minimum jumps if we go through down ; find minimum jumps if we go through right ; return minimum jumps ; 

R = 4
C = 3


def isSafe(x, y):
    return (x < R and y < C)


def minJump(height, x, y):
    if (x == R - 1 and y == C - 1):
        return 0
    diag = 10 ** 9
    if (isSafe(x + 1, y + 1)):
        diag = (minJump(height, x + 1, y + 1) +
                abs(height[x][y] - height[x + 1][y + 1]))
    down = 10 ** 9
    if (isSafe(x + 1, y)):
        down = (minJump(height, x + 1, y) +
                abs(height[x][y] - height[x + 1][y]))
    right = 10 ** 9
    if (isSafe(x, y + 1)):
        right = (minJump(height, x, y + 1) +
                 abs(height[x][y] - height[x][y + 1]))
    return min([down, right, diag])


height = [[5, 4, 2], [9, 2, 1], [2, 5, 9], [1, 3, 11]]
print(minJump(height, 0, 0))

# Expected output:
12
# maximum sum subsequence with at | python3 program to find maximum sum subsequence such that elements are at least k distance away . ; ms [ i ] is going to store maximum sum subsequence in subarray from arr [ i ] to arr [ n - 1 ] ; we fill ms from right to left . ; 
def maxSum(arr, N, k):
    MS = [0 for i in range(N)]
    MS[N - 1] = arr[N - 1]
    for i in range(N - 2, -1, -1):
        if (i + k + 1 >= N):
            MS[i] = max(arr[i], MS[i + 1])
        else:
            MS[i] = max(arr[i] + MS[i + k + 1], MS[i + 1])
    return MS[0]


N = 10
k = 2
arr = [50, 70, 40, 50, 90, 70, 60, 40, 70, 50]
print(maxSum(arr, N, k))

# Expected output:
230
# length of longest balanced subsequence | python3 program to find length of the longest balanced subsequence ; variable to count all the open brace that does not have the corresponding closing brace . ; to count all the close brace that does not have the corresponding open brace . ; iterating over the string ; number of open braces that hasn 't been closed yet. ; number of close braces that cannot be mapped to any open brace . ; mapping the ith close brace to one of the open brace . ; 
def maxLength(s, n):
    invalidOpenBraces = 0
    invalidCloseBraces = 0
    for i in range(n):
        if (s[i] == '('):
            invalidOpenBraces += 1
        else:
            if (invalidOpenBraces == 0):
                invalidCloseBraces += 1
            else:
                invalidOpenBraces -= 1
    return (n - (invalidOpenBraces + invalidCloseBraces))


s = "()(((((()"
n = len(s)
print(maxLength(s, n))

# Expected output:
4
# longest alternating sub | function to calculate alternating sub - array for each index of array elements ; initialize the base state of len [ ] ; calculating value for each element ; if both elements are different then add 1 to next len [ i + 1 ] ; else initialize to 1 ; print lengths of binary subarrays . ; 
def alternateSubarray(arr, n):
    len = []
    for i in range(n + 1):
        len .append(0)
    len[n - 1] = 1
    for i in range(n - 2, -1, -1):
        if (arr[i] ^ arr[i + 1]):
            len[i] = len[i + 1] + 1
        else:
            len[i] = 1
    for i in range(n):
        print(len[i], " ", end="")


arr = [True, False, True, False, False, True]
n = len(arr)
alternateSubarray(arr, n)

# Expected output:
4  3  2  1  2  1
# longest alternating sub | function to calculate alternating sub - array for each index of array elements ; initialize count variable for storing length of sub - array ; initialize ' prev ' variable which indicates the previous element while traversing for index 'i ; if both elements are same , print elements because alternate element is not found for current index ; print count and decrement it . ; increment count for next element ; re - initialize previous variable ; if elements are still available after traversing whole array , print it ; 
def alternateSubarray(arr, n):
    count = 1
    prev = arr[0]
    for i in range(1, n):
        if ((arr[i] ^ prev) == 0):
            while (count):
                print(count, end=" ")
                count -= 1
        count += 1
        prev = arr[i]
    while (count):
        print(count, end=" ")
        count -= 1


if __name__ == '__main__':
    arr = [1, 0, 1, 0, 0, 1]
    n = len(arr)
    alternateSubarray(arr, n)

# Expected output:
4 3 2 1 2 1
# longest common subsequence with at most k changes allowed | python3 program to find lcs of two arrays with k changes allowed in the first array . ; return lcs with at most k changes allowed . ; if at most changes is less than 0. ; if any of two array is over . ; making a reference variable to dp [ n ] [ m ] [ k ] ; if value is already calculated , return that value . ; calculating lcs with no changes made . ; calculating lcs when array element are same . ; calculating lcs with changes made . ; 

MAX = 10


def lcs(dp, arr1, n, arr2, m, k):
    if k < 0:
        return -(10 ** 7)
    if n < 0 or m < 0:
        return 0
    ans = dp[n][m][k]
    if ans != -1:
        return ans
    ans = max(lcs(dp, arr1, n - 1, arr2, m, k),
              lcs(dp, arr1, n, arr2, m - 1, k))
    if arr1[n - 1] == arr2[m - 1]:
        ans = max(ans, 1 + lcs(dp, arr1, n - 1, arr2, m - 1, k))
    ans = max(ans, lcs(dp, arr1, n - 1, arr2, m - 1, k - 1))
    return ans


if __name__ == "__main__":
    k = 1
    arr1 = [1, 2, 3, 4, 5]
    arr2 = [5, 3, 1, 4, 2]
    n = len(arr1)
    m = len(arr2)
    dp = [[[-1 for i in range(MAX)]for j in range(MAX)]for k in range(MAX)]
    print(lcs(dp, arr1, n, arr2, m, k))

# Expected output:
3
# count ways to build street under given constraints | function to count ways of building a street of n rows ; base case ; ways of building houses in both the spots of ith row ; ways of building an office in one of the two spots of ith row ; total ways for n rows ; 
def countWays(n):
    dp = [[0] * (n + 1)for i in range(2)]
    dp[0][1] = 1
    dp[1][1] = 2
    for i in range(2, n + 1):
        dp[0][i] = dp[0][i - 1] + dp[1][i - 1]
        dp[1][i] = (dp[0][i - 1] * 2 + dp[1][i - 1])
    return dp[0][n] + dp[1][n]


if __name__ == "__main__":
    n = 5
    print("Total no of ways with n =", n, "are:", countWays(n))

# Expected output:
Total no of ways with n = 5 are: 99
# count ways to build street under given constraints | program to count ways ; iterate from 2 to n ; 
def countways(n):
    A = [0 for i in range(n + 2)]
    A[0] = 1
    A[1] = 3
    A[2] = 7
    for i in range(2, n + 1):
        A[i] = 2 * A[i - 1] + A[i - 2]
    return A[n]


n = 5
print(countways(5))

# Expected output:
99
# maximum length subsequence with difference between adjacent elements as either 0 or 1 | function to find maximum length subsequence with difference between adjacent elements as either 0 or 1 ; initialize mls [ ] values for all indexes ; compute optimized maximum length subsequence values in bottom up manner ; store maximum of all ' mls ' values in 'max ; required maximum length subsequence ; 
def maxLenSub(arr, n):
    mls = []
    max = 0
    for i in range(n):
        mls.append(1)
    for i in range(n):
        for j in range(i):
            if (abs(arr[i] - arr[j]) <= 1 and mls[i] < mls[j] + 1):
                mls[i] = mls[j] + 1
    for i in range(n):
        if (max < mls[i]):
            max = mls[i]
    return max


arr = [2, 5, 6, 3, 7, 6, 5, 8]
n = len(arr)
print("Maximum length subsequence = ", maxLenSub(arr, n))

# Expected output:
Maximum length subsequence =  5
# coin game winner where every player has three choices | to find winner of game ; to store results ; initial values ; computing other values . ; if a losses any of i - 1 or i - x or i - y game then he will definitely win game i ; else a loses game . ; if dp [ n ] is true then a will game otherwise he losses ; 
def findWinner(x, y, n):
    dp = [0 for i in range(n + 1)]
    dp[0] = False
    dp[1] = True
    for i in range(2, n + 1):
        if (i - 1 >= 0 and not dp[i - 1]):
            dp[i] = True
        elif (i - x >= 0 and not dp[i - x]):
            dp[i] = True
        elif (i - y >= 0 and not dp[i - y]):
            dp[i] = True
        else:
            dp[i] = False
    return dp[n]


x = 3
y = 4
n = 5
if (findWinner(x, y, n)):
    print('A')
else:
    print('B')

# Expected output:
A
# maximum games played by winner | method returns maximum games a winner needs to play in n - player tournament ; for 0 games , 1 player is needed for 1 game , 2 players are required ; loop until i - th fibonacci number is less than or equal to n ; result is ( i - 1 ) because i will be incremented one extra in while loop and we want the last value which is smaller than n , so ; 
def maxGameByWinner(N):
    dp = [0 for i in range(N)]
    dp[0] = 1
    dp[1] = 2
    i = 1
    while dp[i] <= N:
        i = i + 1
        dp[i] = dp[i - 1] + dp[i - 2]
    return (i - 1)


N = 10
print(maxGameByWinner(N))

# Expected output:
4
# convert to strictly increasing integer array with minimum changes | find min elements to remove from array to make it strictly increasing ; mark all elements of lis as 1 ; find lis of array ; return min changes for array to strictly increasing ; 
def minRemove(arr, n):
    LIS = [0 for i in range(n)]
    len = 0
    for i in range(n):
        LIS[i] = 1
    for i in range(1, n):
        for j in range(i):
            if (arr[i] > arr[j] and (i - j) <= (arr[i] - arr[j])):
                LIS[i] = max(LIS[i], LIS[j] + 1)
        len = max(len, LIS[i])
    return (n - len)


arr = [1, 2, 6, 5, 4]
n = len(arr)
print(minRemove(arr, n))

# Expected output:
2
# ways of transforming one string to other by removing 0 or more characters | python3 program to count the distinct transformation of one string to other . ; if b = " " i . e . , an empty string . there is only one way to transform ( remove all characters ) ; fill dp [ ] [ ] in bottom up manner traverse all character of b [ ] ; traverse all characters of a [ ] for b [ i ] ; filling the first row of the dp matrix . ; filling other rows ; 
def countTransformation(a, b):
    n = len(a)
    m = len(b)
    if m == 0:
        return 1
    dp = [[0] * (n)for _ in range(m)]
    for i in range(m):
        for j in range(i, n):
            if i == 0:
                if j == 0:
                    if a[j] == b[i]:
                        dp[i][j] = 1
                    else:
                        dp[i][j] = 0
                elif a[j] == b[i]:
                    dp[i][j] = dp[i][j - 1] + 1
                else:
                    dp[i][j] = dp[i][j - 1]
            else:
                if a[j] == b[i]:
                    dp[i][j] = (dp[i][j - 1] + dp[i - 1][j - 1])
                else:
                    dp[i][j] = dp[i][j - 1]
    return dp[m - 1][n - 1]


if __name__ == "__main__":
    a = "abcccdf"
    b = "abccdf"
    print(countTransformation(a, b))

# Expected output:
3
# n | python code to find nth number with digits 0 , 1 , 2 , 3 , 4 , 5 ; function to convert num to base 6 ; 

max = 100000


def baseconversion(arr, num, base):
    i = 0
    if (num == 0):
        return 0
    while (num > 0):
        rem = num % base
        i = i + 1
        arr[i] = rem
        num = num // base
    return i


if __name__ == '__main__':
    arr = [0 for i in range(max)]
    n = 10
    size = baseconversion(arr, n - 1, 6)
    if (size == 0):
        print(size)
    for i in range(size, 0, -1):
        print(arr[i], end="")

# Expected output:
13
# find length of longest subsequence of one string which is substring of another string | python3 program to find maximum length of subsequence of a string x such it is substring in another string y . ; return the maximum size of substring of x which is substring in y . ; calculating value for each element . ; if alphabet of string x and y are equal make dp [ i ] [ j ] = 1 + dp [ i - 1 ] [ j - 1 ] ; else copy the previous value in the row i . e dp [ i - 1 ] [ j - 1 ] ; finding the maximum length ; 

MAX = 1000


def maxSubsequenceSubstring(x, y, n, m):
    dp = [[0 for i in range(MAX)]for i in range(MAX)]
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if (x[j - 1] == y[i - 1]):
                dp[i][j] = 1 + dp[i - 1][j - 1]
            else:
                dp[i][j] = dp[i][j - 1]
    ans = 0
    for i in range(1, m + 1):
        ans = max(ans, dp[i][n])
    return ans


x = "ABCD"
y = "BACDBDCD"
n = len(x)
m = len(y)
print(maxSubsequenceSubstring(x, y, n, m))

# Expected output:
3
# choose maximum weight with given weight and value ratio | python3 program to choose item with maximum sum of weight under given constraint ; base cases : if no item is remaining ; first make pair with last chosen item and difference between weight and values ; choose maximum value from following two 1 ) not selecting the current item and calling recursively 2 ) selection current item , including the weight and updating the difference before calling recursively ; method returns maximum sum of weight with k as ration of sum of weight and their values ; 

INT_MIN = -9999999999


def maxWeightRec(wt, val, K, mp, last, diff):
    if last == -1:
        if diff == 0:
            return 0
        else:
            return INT_MIN
    tmp = (last, diff)
    if tmp in mp:
        return mp[tmp]
    mp[tmp] = max(
        maxWeightRec(
            wt,
            val,
            K,
            mp,
            last -
            1,
            diff),
        wt[last] +
        maxWeightRec(
            wt,
            val,
            K,
            mp,
            last -
            1,
            diff +
            wt[last] -
            val[last] *
            K))
    return mp[tmp]


def maxWeight(wt, val, K, N):
    return maxWeightRec(wt, val, K, {}, N - 1, 0)


if __name__ == "__main__":
    wt = [4, 8, 9]
    val = [2, 4, 6]
    N = len(wt)
    K = 2
    print(maxWeight(wt, val, K, N))

# Expected output:
12
# pyramid form ( increasing then decreasing ) consecutive array using reduce operations | returns minimum cost to form a pyramid ; store the maximum possible pyramid height ; maximum height at start is 1 ; for each position calculate maximum height ; maximum height at end is 1 ; for each position calculate maximum height ; find minimum possible among calculated values ; find maximum height of pyramid ; calculate cost of this pyramid ; calculate cost of left half ; calculate cost of right half ; 
def minPyramidCost(arr: list, N):
    left = [0] * N
    right = [0] * N
    left[0] = min(arr[0], 1)
    for i in range(1, N):
        left[i] = min(arr[i], min(left[i - 1] + 1, i + 1))
    right[N - 1] = min(arr[N - 1], 1)
    for i in range(N - 2, -1, -1):
        right[i] = min(arr[i], min(right[i + 1] + 1, N - i))
    tot = [0] * N
    for i in range(N):
        tot[i] = min(right[i], left[i])
    max_ind = 0
    for i in range(N):
        if tot[i] > tot[max_ind]:
            max_ind = i
    cost = 0
    height = tot[max_ind]
    for x in range(max_ind, -1, -1):
        cost += arr[x] - height
        if height > 0:
            height -= 1
    height = tot[max_ind] - 1
    for x in range(max_ind + 1, N):
        cost += arr[x] - height
        if height > 0:
            height -= 1
    return cost


if __name__ == "__main__":
    arr = [1, 2, 3, 4, 2, 1]
    N = len(arr)
    print(minPyramidCost(arr, N))

# Expected output:
4
# maximum sum in a 2 x n grid such that no two elements are adjacent | function to find max sum without adjacent ; sum including maximum element of first column ; not including first column 's element ; traverse for further elements ; update max_sum on including or excluding of previous column ; include current column . add maximum element from both row of current column ; if current column doesn 't to be included ; return maximum of excl and incl as that will be the maximum sum ; 
def maxSum(grid, n):
    incl = max(grid[0][0], grid[1][0])
    excl = 0
    for i in range(1, n):
        excl_new = max(excl, incl)
        incl = excl + max(grid[0][i], grid[1][i])
        excl = excl_new
    return max(excl, incl)


if __name__ == "__main__":
    grid = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
    n = 5
    print(maxSum(grid, n))

# Expected output:
24
# minimum insertions to sort an array | method returns min steps of insertion we need to perform to sort array 'arr ; lis [ i ] is going to store length of lis that ends with i . ; initialize lis values for all indexes ; compute optimized lis values in bottom up manner ; the overall lis must end with of the array elements . pick maximum of all lis values ; return size of array minus length of lis as final result ; 
def minInsertionStepToSortArray(arr, N):
    lis = [0] * N
    for i in range(N):
        lis[i] = 1
    for i in range(1, N):
        for j in range(i):
            if (arr[i] >= arr[j] and lis[i] < lis[j] + 1):
                lis[i] = lis[j] + 1
    max = 0
    for i in range(N):
        if (max < lis[i]):
            max = lis[i]
    return (N - max)


if __name__ == "__main__":
    arr = [2, 3, 5, 1, 4, 7, 6]
    N = len(arr)
    print(minInsertionStepToSortArray(arr, N))

# Expected output:
3
# print all distinct characters of a string in order ( 3 methods ) | python3 program to print distinct characters of a string . ; print duplicates present in the passed string ; create an array of size 256 and count of every character in it ; count array with frequency of characters ; print characters having count more than 0 ; 

NO_OF_CHARS = 256


def printDistinct(str):
    count = [0] * NO_OF_CHARS
    for i in range(len(str)):
        if (str[i] != ' '):
            count[ord(str[i])] += 1
    n = i
    for i in range(n):
        if (count[ord(str[i])] == 1):
            print(str[i], end="")


if __name__ == "__main__":
    str = "GeeksforGeeks"
    printDistinct(str)

# Expected output:
for