giulio98/xlcost-single-prompt huggingface dataset:
# paper cut into minimum number of squares | set 2 | python3 program to find minimum number of squares to cut a paper using dynamic programming ; returns min number of squares needed ; initializing max values to vertical_min and horizontal_min ; n = 11 & m = 13 is a special case ; if the given rectangle is already a square ; if the answer for the given rectangle is previously calculated return that answer ; the rectangle is cut horizontally and vertically into two parts and the cut with minimum value is found for every recursive call . ; calculating the minimum answer for the rectangles with width equal to n and length less than m for finding the cut point for the minimum answer ; calculating the minimum answer for the rectangles with width equal to n and length less than m for finding the cut point for the minimum answer ; minimum of the vertical cut or horizontal cut to form a square is the answer ; 

MAX = 300
dp = [[0 for i in range(MAX)]for i in range(MAX)]


def minimumSquare(m, n):
    vertical_min = 10000000000
    horizontal_min = 10000000000
    if n == 13 and m == 11:
        return 6
    if m == 13 and n == 11:
        return 6
    if m == n:
        return 1
    if dp[m][n] != 0:
        return dp[m][n]
    for i in range(1, m // 2 + 1):
        horizontal_min = min(
            minimumSquare(
                i,
                n) +
            minimumSquare(
                m -
                i,
                n),
            horizontal_min)
    for j in range(1, n // 2 + 1):
        vertical_min = min(
            minimumSquare(
                m,
                j) +
            minimumSquare(
                m,
                n -
                j),
            vertical_min)
    dp[m][n] = min(vertical_min, horizontal_min)
    return dp[m][n]


if __name__ == '__main__':
    m = 30
    n = 35
    print(minimumSquare(m, n))

# Expected output:
5
# number of n | returns factorial of n ; returns ncr ; 
def fact(n):
    res = 1
    for i in range(2, n + 1):
        res = res * i
    return res


def nCr(n, r):
    return fact(n) // ((fact(r) * fact(n - r)))


n = 2
print("Number of Non-Decreasing digits: ", nCr(n + 9, 9))

# Expected output:
Number of Non-Decreasing digits:  55
# painting fence algorithm | returns count of ways to color k posts using k colors ; there are k ways to color first post ; there are 0 ways for single post to violate ( same color_ and k ways to not violate ( different color ) ; fill for 2 posts onwards ; current same is same as previous diff ; we always have k - 1 choices for next post ; total choices till i . ; 
def countWays(n, k):
    total = k
    mod = 1000000007
    same, diff = 0, k
    for i in range(2, n + 1):
        same = diff
        diff = total * (k - 1)
        diff = diff % mod
        total = (same + diff) % mod
    return total


if __name__ == "__main__":
    n, k = 3, 2
    print(countWays(n, k))

# Expected output:
6
# sum of all substrings of a string representing a number | set 2 ( constant extra space ) | returns sum of all substring of num ; initialize result ; here traversing the array in reverse order . initializing loop from last element . mf is multiplying factor . ; each time sum is added to its previous sum . multiplying the three factors as explained above . int ( s [ i ] ) is done to convert char to int . ; making new multiplying factor as explained above . ; 
def sumOfSubstrings(num):
    sum = 0
    mf = 1
    for i in range(len(num) - 1, -1, -1):
        sum = sum + (int(num[i])) * (i + 1) * mf
        mf = mf * 10 + 1
    return sum


if __name__ == '__main__':
    num = "6759"
    print(sumOfSubstrings(num))

# Expected output:
8421
# largest sum subarray with at | returns maximum sum of a subarray with at - least k elements . ; maxsum [ i ] is going to store maximum sum till index i such that a [ i ] is part of the sum . ; we use kadane 's algorithm to fill maxsum[]  below code is taken from method3 of  https:www.geeksforgeeks.org/largest-sum-contiguous-subarray/ ; sum of first k elements ; use the concept of sliding window ; compute sum of k elements ending with a [ i ] . ; update result if required ; include maximum sum till [ i - k ] also if it increases overall max . ; 
def maxSumWithK(a, n, k):
    maxSum = [0 for i in range(n)]
    maxSum[0] = a[0]
    curr_max = a[0]
    for i in range(1, n):
        curr_max = max(a[i], curr_max + a[i])
        maxSum[i] = curr_max
    sum = 0
    for i in range(k):
        sum += a[i]
    result = sum
    for i in range(k, n):
        sum = sum + a[i] - a[i - k]
        result = max(result, sum)
        result = max(result, sum + maxSum[i - k])
    return result


a = [1, 2, 3, -10, -3]
k = 4
n = len(a)
print(maxSumWithK(a, n, k))

# Expected output:
-4
# sequences of given length where every element is more than or equal to twice of previous | recursive function to find the number of special sequences ; a special sequence cannot exist if length n is more than the maximum value m . ; if n is 0 , found an empty special sequence ; there can be two possibilities : ( 1 ) reduce last element value ( 2 ) consider last element as m and reduce number of terms ; 
def getTotalNumberOfSequences(m, n):
    if m < n:
        return 0
    if n == 0:
        return 1
    res = (getTotalNumberOfSequences(m - 1, n) +
           getTotalNumberOfSequences(m // 2, n - 1))
    return res


if __name__ == '__main__':
    m = 10
    n = 4
    print('Total number of possible sequences:',
          getTotalNumberOfSequences(m, n))

# Expected output:
Total number of possible sequences: 4
# sequences of given length where every element is more than or equal to twice of previous | dp based function to find the number of special sequence ; define t and build in bottom manner to store number of special sequences of length n and maximum value m ; base case : if length of sequence is 0 or maximum value is 0 , there cannot exist any special sequence ; if length of sequence is more than the maximum value , special sequence cannot exist ; if length of sequence is 1 then the number of special sequences is equal to the maximum value for example with maximum value 2 and length 1 , there can be 2 special sequences { 1 } , { 2 } ; otherwise calculate ; 
def getTotalNumberOfSequences(m, n):
    T = [[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:
                T[i][j] = 0
            elif i < j:
                T[i][j] = 0
            elif j == 1:
                T[i][j] = i
            else:
                T[i][j] = T[i - 1][j] + T[i // 2][j - 1]
    return T[m][n]


if __name__ == '__main__':
    m = 10
    n = 4
    print('Total number of possible sequences ',
          getTotalNumberOfSequences(m, n))

# Expected output:
Total number of possible sequences  4
# minimum number of deletions and insertions to transform one string into another | returns length of length common subsequence for str1 [ 0. . m - 1 ] , str2 [ 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 str1 [ 0. . i - 1 ] and str2 [ 0. . j - 1 ] ; l [ m ] [ n ] contains length of lcs for x [ 0. . n - 1 ] and y [ 0. . m - 1 ] ; function to find minimum number of deletions and insertions ; 
def lcs(str1, str2, 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 (str1[i - 1] == str2[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 printMinDelAndInsert(str1, str2):
    m = len(str1)
    n = len(str2)
    leng = lcs(str1, str2, m, n)
    print("Minimum number of deletions = ", m - leng, sep=' ')
    print("Minimum number of insertions = ", n - leng, sep=' ')


str1 = "heap"
str2 = "pea"
printMinDelAndInsert(str1, str2)

# Expected output:
Minimum number of deletions =  2
Minimum number of insertions =  1
# minimum number of deletions to make a sorted sequence | lis ( ) returns the length of the longest increasing subsequence in arr [ ] of size n ; initialize lis values for all indexes ; compute optimized lis values in bottom up manner ; pick resultimum of all lis values ; function to calculate minimum number of deletions ; find longest increasing subsequence ; after removing elements other than the lis , we get sorted sequence . ; 
def lis(arr, n):
    result = 0
    lis = [0 for i in range(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
    for i in range(n):
        if (result < lis[i]):
            result = lis[i]
    return result


def minimumNumberOfDeletions(arr, n):
    len = lis(arr, n)
    return (n - len)


arr = [30, 40, 2, 5, 1, 7, 45, 50, 8]
n = len(arr)
print("Minimum number of deletions = ", minimumNumberOfDeletions(arr, n))

# Expected output:
Minimum number of deletions =  4
# clustering / partitioning an array such that sum of square differences is minimum | python3 program to find minimum cost k partitions of array . ; returns minimum cost of partitioning a [ ] in k clusters . ; create a dp [ ] [ ] table and initialize all values as infinite . dp [ i ] [ j ] is going to store optimal partition cost for arr [ 0. . i - 1 ] and j partitions ; fill dp [ ] [ ] in bottom up manner ; current ending position ( after i - th iteration result for a [ 0. . i - 1 ] is computed . ; j is number of partitions ; picking previous partition for current i . ; 

inf = 1000000000


def minCost(a, n, k):
    dp = [[inf for i in range(k + 1)]for j in range(n + 1)]
    dp[0][0] = 0
    for i in range(1, n + 1):
        for j in range(1, k + 1):
            for m in range(i - 1, -1, -1):
                dp[i][j] = min(dp[i][j], dp[m][j - 1] +
                               (a[i - 1] - a[m]) * (a[i - 1] - a[m]))
    return dp[n][k]


if __name__ == '__main__':
    k = 2
    a = [1, 5, 8, 10]
    n = len(a)
    print(minCost(a, n, k))

# Expected output:
20
# minimum number of deletions to make a string palindrome | returns the length of the longest palindromic subsequence in 'str ; create a table to store results of subproblems ; strings of length 1 are palindrome of length 1 ; build the table . note that the lower diagonal values of table are useless and not filled in the process . c1 is length of substring ; length of longest palindromic subseq ; function to calculate minimum number of deletions ; find longest palindromic subsequence ; after removing characters other than the lps , we get palindrome . ; 
def lps(str):
    n = len(str)
    L = [[0 for x in range(n)]for y in range(n)]
    for i in range(n):
        L[i][i] = 1
    for cl in range(2, n + 1):
        for i in range(n - cl + 1):
            j = i + cl - 1
            if (str[i] == str[j] and cl == 2):
                L[i][j] = 2
            elif (str[i] == str[j]):
                L[i][j] = L[i + 1][j - 1] + 2
            else:
                L[i][j] = max(L[i][j - 1], L[i + 1][j])
    return L[0][n - 1]


def minimumNumberOfDeletions(str):
    n = len(str)
    l = lps(str)
    return (n - l)


if __name__ == "__main__":
    str = "geeksforgeeks"
    print("Minimum number of deletions = ", minimumNumberOfDeletions(str))

# Expected output:
Minimum number of deletions =  8
# temple offerings | returns minimum offerings required ; go through all templs one by one ; go to left while height keeps increasing ; go to right while height keeps increasing ; this temple should offer maximum of two values to follow the rule . ; 
def offeringNumber(n, templeHeight):
    sum = 0
    for i in range(n):
        left = 0
        right = 0
        for j in range(i - 1, -1, -1):
            if (templeHeight[j] < templeHeight[j + 1]):
                left += 1
            else:
                break
        for j in range(i + 1, n):
            if (templeHeight[j] < templeHeight[j - 1]):
                right += 1
            else:
                break
        sum += max(right, left) + 1
    return sum


arr1 = [1, 2, 2]
print(offeringNumber(3, arr1))
arr2 = [1, 4, 3, 6, 2, 1]
print(offeringNumber(6, arr2))

# Expected output:
4
10
# subset with sum divisible by m | returns true if there is a subset of arr [ ] with sum divisible by m ; this array will keep track of all the possible sum ( after modulo m ) which can be made using subsets of arr [ ] initialising boolean array with all false ; we 'll loop through all the elements of arr[] ; anytime we encounter a sum divisible by m , we are done ; to store all the new encountered sum ( after modulo ) . it is used to make sure that arr [ i ] is added only to those entries for which dp [ j ] was true before current iteration . ; for each element of arr [ ] , we loop through all elements of dp table from 1 to m and we add current element i . e . , arr [ i ] to all those elements which are true in dp table ; if an element is true in dp table ; we update it in temp and update to dp once loop of j is over ; updating all the elements of temp to dp table since iteration over j is over ; also since arr [ i ] is a single element subset , arr [ i ] % m is one of the possible sum ; 
def modularSum(arr, n, m):
    if (n > m):
        return True
    DP = [False for i in range(m)]
    for i in range(n):
        if (DP[0]):
            return True
        temp = [False for i in range(m)]
        for j in range(m):
            if (DP[j]):
                if (DP[(j + arr[i]) % m] == False):
                    temp[(j + arr[i]) % m] = True
        for j in range(m):
            if (temp[j]):
                DP[j] = True
        DP[arr[i] % m] = True
    return DP[0]


arr = [1, 7]
n = len(arr)
m = 5
print("YES")if (modularSum(arr, n, m))else print("NO")

# Expected output:
NO
# maximum sum of a path in a right number triangle | tri [ ] [ ] is a 2d array that stores the triangle , n is number of lines or rows . ; adding the element of row 1 to both the elements of row 2 to reduce a step from the loop ; traverse remaining rows ; loop to traverse columns ; tri [ i ] would store the possible combinations of sum of the paths ; array at n - 1 index ( tri [ i ] ) stores all possible adding combination , finding the maximum one out of them ; 
def maxSum(tri, n):
    if n > 1:
        tri[1][1] = tri[1][1] + tri[0][0]
        tri[1][0] = tri[1][0] + tri[0][0]
    for i in range(2, n):
        tri[i][0] = tri[i][0] + tri[i - 1][0]
        tri[i][i] = tri[i][i] + tri[i - 1][i - 1]
        for j in range(1, i):
            if tri[i][j] + tri[i - 1][j - 1] >= tri[i][j] + tri[i - 1][j]:
                tri[i][j] = tri[i][j] + tri[i - 1][j - 1]
            else:
                tri[i][j] = tri[i][j] + tri[i - 1][j]
    print(max(tri[n - 1]))


tri = [[1], [2, 1], [3, 3, 2]]
maxSum(tri, 3)

# Expected output:
6
# modify array to maximize sum of adjacent differences | returns maximum - difference - sum with array modifications allowed . ; initialize dp [ ] [ ] with 0 values . ; for [ i + 1 ] [ 0 ] ( i . e . current modified value is 1 ) , choose maximum from dp [ i ] [ 0 ] + abs ( 1 - 1 ) = dp [ i ] [ 0 ] and dp [ i ] [ 1 ] + abs ( 1 - arr [ i ] ) ; for [ i + 1 ] [ 1 ] ( i . e . current modified value is arr [ i + 1 ] ) , choose maximum from dp [ i ] [ 0 ] + abs ( arr [ i + 1 ] - 1 ) and dp [ i ] [ 1 ] + abs ( arr [ i + 1 ] - arr [ i ] ) ; 
def maximumDifferenceSum(arr, N):
    dp = [[0, 0]for i in range(N)]
    for i in range(N):
        dp[i][0] = dp[i][1] = 0
    for i in range(N - 1):
        dp[i + 1][0] = max(dp[i][0], dp[i][1] + abs(1 - arr[i]))
        dp[i + 1][1] = max(dp[i][0] + abs(arr[i + 1] - 1),
                           dp[i][1] + abs(arr[i + 1] - arr[i]))
    return max(dp[N - 1][0], dp[N - 1][1])


if __name__ == '__main__':
    arr = [3, 2, 1, 4, 5]
    N = len(arr)
    print(maximumDifferenceSum(arr, N))

# Expected output:
8
# 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 ; if we had saw this combination previously ; three cases , we choose , a or b or c in all three cases n decreases by 1. ; a wrapper over countstrutil ( ) ; 
def countStrUtil(dp, n, bCount=1, cCount=2):
    if (bCount < 0 or cCount < 0):
        return 0
    if (n == 0):
        return 1
    if (bCount == 0 and cCount == 0):
        return 1
    if (dp[n][bCount][cCount] != -1):
        return dp[n][bCount][cCount]
    res = countStrUtil(dp, n - 1, bCount, cCount)
    res += countStrUtil(dp, n - 1, bCount - 1, cCount)
    res += countStrUtil(dp, n - 1, bCount, cCount - 1)
    dp[n][bCount][cCount] = res
    return dp[n][bCount][cCount]


def countStr(n):
    dp = [[[-1 for x in range(n + 2)]for y in range(3)]for z in range(4)]
    return countStrUtil(dp, n)


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

# Expected output:
19
# probability of knight to remain in the chessboard | size of the chessboard ; direction vector for the knight ; returns true if the knight is inside the chessboard ; bottom up approach for finding the probability to go out of chessboard . ; dp array ; for 0 number of steps , each position will have probability 1 ; for every number of steps s ; for every position ( x , y ) after s number of steps ; for every position reachable from ( x , y ) ; if this position lie inside the board ; store the result ; return the result ; number of steps ; 

N = 8
dx = [1, 2, 2, 1, -1, -2, -2, -1]
dy = [2, 1, -1, -2, -2, -1, 1, 2]


def inside(x, y):
    return (x >= 0 and x < N and y >= 0 and y < N)


def findProb(start_x, start_y, steps):
    dp1 = [[[0 for i in range(N + 5)]for j in range(N + 5)]
           for k in range(steps + 5)]
    for i in range(N):
        for j in range(N):
            dp1[i][j][0] = 1
    for s in range(1, steps + 1):
        for x in range(N):
            for y in range(N):
                prob = 0.0
                for i in range(8):
                    nx = x + dx[i]
                    ny = y + dy[i]
                    if (inside(nx, ny)):
                        prob += dp1[nx][ny][s - 1] / 8.0
                dp1[x][y][s] = prob
    return dp1[start_x][start_y][steps]


K = 3
print(findProb(0, 0, K))

# Expected output:
0.125
# count of subarrays whose maximum element is greater than k | return number of subarrays whose maximum element is less than or equal to k . ; to store count of subarrays with all elements less than or equal to k . ; traversing the array . ; if element is greater than k , ignore . ; counting the subarray length whose each element is less than equal to k . ; suming number of subarray whose maximum element is less than equal to k . ; 
def countSubarray(arr, n, k):
    s = 0
    i = 0
    while (i < n):
        if (arr[i] > k):
            i = i + 1
            continue
        count = 0
        while (i < n and arr[i] <= k):
            i = i + 1
            count = count + 1
        s = s + ((count * (count + 1)) // 2)
    return (n * (n + 1) // 2 - s)


arr = [1, 2, 3]
k = 2
n = len(arr)
print(countSubarray(arr, n, k))

# Expected output:
3
# sum of average of all subsets | 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 ; method returns sum of average of all subsets ; find sum of elements ; looping once for all subset of same size ; each element occurs ncr ( n - 1 , n - 1 ) times while considering subset of size n ; 
def nCr(n, k):
    C = [[0 for i in range(k + 1)]for j in range(n + 1)]
    for i in range(n + 1):
        for j in range(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 resultOfAllSubsets(arr, N):
    sum = 0
    result = 0
    for i in range(N):
        sum += arr[i]
    for n in range(1, N + 1):
        result += (sum * (nCr(N - 1, n - 1))) / n
    return result


arr = [2, 3, 5, 7]
N = len(arr)
print(resultOfAllSubsets(arr, N))

# Expected output:
63.75
# maximum subsequence sum such that no three are consecutive | python3 program to find the maximum sum such that no three are consecutive using recursion . ; returns maximum subsequence sum such that no three elements are consecutive ; 3 base cases ( process first three elements ) ; process rest of the elements we have three cases ; 

arr = [100, 1000, 100, 1000, 1]
sum = [-1] * 10000


def maxSumWO3Consec(n):

    if (sum[n] != -1):
        return sum[n]

    if (n == 0):
        sum[n] = 0
        return sum[n]

    if (n == 1):
        sum[n] = arr[0]
        return sum[n]

    if (n == 2):
        sum[n] = arr[1] + arr[0]
        return sum[n]

    sum[n] = max(max(maxSumWO3Consec(n - 1),
                     maxSumWO3Consec(n - 2) + arr[n-1]),
                 arr[n-1] + arr[n - 2] +
                 maxSumWO3Consec(n - 3))

    return sum[n]


if __name__ == "__main__":
    n = len(arr)
    print(maxSumWO3Consec(n))

# Expected output:
2101
# maximum sum of pairs with specific difference | method to return maximum sum we can get by finding less than k difference pairs ; sort elements to ensure every i and i - 1 is closest possible pair ; to get maximum possible sum , iterate from largest to smallest , giving larger numbers priority over smaller numbers . ; case i : diff of arr [ i ] and arr [ i - 1 ] is less then k , add to maxsum case ii : diff between arr [ i ] and arr [ i - 1 ] is not less then k , move to next i since with sorting we know , arr [ i ] - arr [ i - 1 ] < arr [ i ] - arr [ i - 2 ] and so on . ; assuming only positive numbers . ; when a match is found skip this pair ; 
def maxSumPairWithDifferenceLessThanK(arr, N, k):
    maxSum = 0
    arr .sort()
    i = N - 1
    while (i > 0):
        if (arr[i] - arr[i - 1] < k):
            maxSum += arr[i]
            maxSum += arr[i - 1]
            i -= 1
        i -= 1
    return maxSum


arr = [3, 5, 10, 15, 17, 12, 9]
N = len(arr)
K = 4
print(maxSumPairWithDifferenceLessThanK(arr, N, K))

# Expected output:
62
# count digit groupings of a number with given constraints | function to find the subgroups ; terminating condition ; 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 ; 
def countGroups(position, previous_sum, length, num):
    if (position == length):
        return 1
    res = 0
    sum = 0
    for i in range(position, length):
        sum = sum + int(num[i])
        if (sum >= previous_sum):
            res = res + countGroups(i + 1, sum, length, num)
    return res


if __name__ == '__main__':
    num = "1119"
    len = len(num)
    print(countGroups(0, 0, len, num))

# Expected output:
7