giulio98/xlcost-single-prompt huggingface dataset:
# smallest number with given sum of digits and sum of square of digits | python3 program to find the smallest number with given sum of digits and sum of square of digits ; top down dp to find minimum number of digits with given sum of dits a and sum of square of digits as b ; invalid condition ; number of digits satisfied ; memoization ; initialize ans as maximum as we have to find the minimum number of digits ; check for all possible combinations of digits ; recurrence call ; if the combination of digits cannot give sum as a and sum of square of digits as b ; returns the minimum number of digits ; function to print the digits that gives sum as a and sum of square of digits as b ; initialize the dp array as ; base condition ; function call to get the minimum number of digits ; when there does not exists any number ; printing the digits from the most significant digit ; trying all combinations ; checking conditions for minimum digits ; 

dp = [[-1 for i in range(8101)]for i in range(901)]


def minimumNumberOfDigits(a, b):
    if (a > b or a < 0 or b < 0 or a > 900 or b > 8100):
        return -1
    if (a == 0 and b == 0):
        return 0
    if (dp[a][b] != -1):
        return dp[a][b]
    ans = 101
    for i in range(9, 0, -1):
        k = minimumNumberOfDigits(a - i, b - (i * i))
        if (k != -1):
            ans = min(ans, k + 1)
    dp[a][b] = ans
    return ans


def printSmallestNumber(a, b):
    for i in range(901):
        for j in range(8101):
            dp[i][j] = -1
    dp[0][0] = 0
    k = minimumNumberOfDigits(a, b)
    if (k == -1 or k > 100):
        print(-1, end='')
    else:
        while (a > 0 and b > 0):
            for i in range(1, 10):
                if (a >= i and b >= i * i and 1 +
                        dp[a - i][b - i * i] == dp[a][b]):
                    print(i, end='')
                    a -= i
                    b -= i * i
                    break


if __name__ == '__main__':
    a = 18
    b = 162
    printSmallestNumber(a, b)

# Expected output:
99
# sum of product of consecutive binomial coefficients | python3 program to find sum of product of consecutive binomial coefficient . ; find the binomial coefficient up to nth term ; c [ 0 ] = 1 ; nc0 is 1 ; compute next row of pascal triangle using the previous row ; return the sum of the product of consecutive binomial coefficient . ; 

MAX = 100


def binomialCoeff(n, k):
    C = [0] * (k + 1)
    for i in range(1, n + 1):
        for j in range(min(i, k), 0, -1):
            C[j] = C[j] + C[j - 1]
    return C[k]


def sumOfproduct(n):
    return binomialCoeff(2 * n, n - 1)


n = 3
print(sumOfproduct(n))

# Expected output:
0
# check if array sum can be made k by three operations on it | python program to find if array can have sum of k by applying three types of possible operations on it ; check if it is possible to achieve a sum with three operation allowed ; if sum id negative . ; if going out of bound . ; if sum is achieved . ; if the current state is not evaluated yet . ; replacing element with negative value of the element . ; substracting index number from the element . ; adding index number to the element . ; wrapper function ; 

MAX = 100


def check(i, add, n, k, a, dp):
    if add <= 0:
        return False
    if i >= n:
        if add == k:
            return True
        return False
    if dp[i][add] != -1:
        return dp[i][add]
    dp[i][add] = (
        check(
            i + 1,
            add - 2 * a[i],
            n,
            k,
            a,
            dp) or check(
            i + 1,
            add,
            n,
            k,
            a,
            dp))
    dp[i][add] = (check(i + 1, add - (i + 1), n, k, a, dp) or dp[i][add])
    dp[i][add] = (check(i + 1, add + i + 1, n, k, a, dp) or dp[i][add])
    return dp[i][add]


def wrapper(n, k, a):
    add = 0
    for i in range(n):
        add += a[i]
    dp = [-1] * MAX
    for i in range(MAX):
        dp[i] = [-1] * MAX
    return check(0, add, n, k, a, dp)


if __name__ == "__main__":
    a = [1, 2, 3, 4]
    n = 4
    k = 5
    print("Yes")if wrapper(n, k, a)else print("No")

# Expected output:
Yes
# print fibonacci sequence using 2 variables | simple python3 program to print fibonacci sequence ; 
def fib(n):
    a = 0
    b = 1
    if (n >= 0):
        print(a, end=' ')
    if (n >= 1):
        print(b, end=' ')
    for i in range(2, n + 1):
        c = a + b
        print(c, end=' ')
        a = b
        b = c


fib(9)

# Expected output:
0 1 1 2 3 5 8 13 21 34
# maximum sum increasing subsequence from a prefix and a given element after prefix is must | python3 program to find maximum sum increasing subsequence till i - th index and including k - th index . ; initializing the first row of the dp [ ] [ ] ; creating the dp [ ] [ ] matrix . ; to calculate for i = 4 and k = 6. ; 
def pre_compute(a, n, index, k):
    dp = [[0 for i in range(n)]for i in range(n)]
    for i in range(n):
        if a[i] > a[0]:
            dp[0][i] = a[i] + a[0]
        else:
            dp[0][i] = a[i]
    for i in range(1, n):
        for j in range(n):
            if a[j] > a[i] and j > i:
                if dp[i - 1][i] + a[j] > dp[i - 1][j]:
                    dp[i][j] = dp[i - 1][i] + a[j]
                else:
                    dp[i][j] = dp[i - 1][j]
            else:
                dp[i][j] = dp[i - 1][j]
    return dp[index][k]


a = [1, 101, 2, 3, 100, 4, 5]
n = len(a)
index = 4
k = 6
print(pre_compute(a, n, index, k))

# Expected output:
11
# moser | function to generate nth term of moser - de bruijn sequence ; s ( 2 * n ) = 4 * s ( n ) ; s ( 2 * n + 1 ) = 4 * s ( n ) + 1 ; generating the first ' n ' terms of moser - de bruijn sequence ; 
def gen(n):
    S = [0, 1]
    for i in range(2, n + 1):
        if i % 2 == 0:
            S .append(4 * S[int(i / 2)])
        else:
            S .append(4 * S[int(i / 2)] + 1)
    z = S[n]
    return z


def moserDeBruijn(n):
    for i in range(n):
        print(gen(i), end=" ")


n = 15
print("First", n, "terms of ", "Moser-de Brujn Sequence:")
moserDeBruijn(n)

# Expected output:
First 15 terms of  Moser-de Brujn Sequence:
0 1 4 5 16 17 20 21 64 65 68 69 80 81 84
# longest common substring ( space optimized dp solution ) | space optimized python3 implementation of longest common substring . ; function to find longest common substring . ; find length of both the strings . ; variable to store length of longest common substring . ; matrix to store result of two consecutive rows at a time . ; variable to represent which row of matrix is current row . ; for a particular value of i and j , len_mat [ currrow ] [ j ] stores length of longest common substring in string x [ 0. . i ] and y [ 0. . j ] . ; make current row as previous row and previous row as new current row . ; 

import numpy as np


def LCSubStr(X, Y):
    m = len(X)
    n = len(Y)
    result = 0
    len_mat = np .zeros((2, n))
    currRow = 0
    for i in range(m):
        for j in range(n):
            if (i == 0 | j == 0):
                len_mat[currRow][j] = 0
            elif (X[i - 1] == Y[j - 1]):
                len_mat[currRow][j] = len_mat[1 - currRow][j - 1] + 1
                result = max(result, len_mat[currRow][j])
            else:
                len_mat[currRow][j] = 0
        currRow = 1 - currRow
    return result


if __name__ == "__main__":
    X = "GeeksforGeeks"
    Y = "GeeksQuiz"
    print(LCSubStr(X, Y))

# Expected output:
5.0
# minimal moves to form a string by adding characters or appending string itself | python program to print the minimal moves to form a string by appending string and adding characters ; function to return the minimal number of moves ; initializing dp [ i ] to int_max ; initialize both strings to null ; base case ; check if it can be appended ; addition of character takes one step ; appending takes 1 step , and we directly reach index i * 2 + 1 after appending so the number of steps is stord in i * 2 + 1 ; 

INT_MAX = 100000000


def minimalSteps(s, n):
    dp = [INT_MAX for i in range(n)]
    s1 = ""
    s2 = ""
    dp[0] = 1
    s1 += s[0]
    for i in range(1, n):
        s1 += s[i]
        s2 = s[i + 1:i + 1 + i + 1]
        dp[i] = min(dp[i], dp[i - 1] + 1)
        if (s1 == s2):
            dp[i * 2 + 1] = min(dp[i] + 1, dp[i * 2 + 1])
    return dp[n - 1]


s = "aaaaaaaa"
n = len(s)
print(minimalSteps(s, n))

# Expected output:
4
# check if any valid sequence is divisible by m | function to check if any valid sequence is divisible by m ; declare mod array ; calculate the mod array ; check if sum is divisible by m ; check if sum is not divisible by 2 ; remove the first element from the modarray since it is not possible to place minus on the first element ; decrease the size of array ; sort the array ; loop until the pointer cross each other ; check if sum becomes equal ; increase and decrease the pointer accordingly ; 
def func(n, m, A):
    ModArray = [0] * n
    Sum = 0
    for i in range(n):
        ModArray[i] = A[i] % m
        Sum += ModArray[i]
    Sum = Sum % m
    if (Sum % m == 0):
        print("True")
        return
    if (Sum % 2 != 0):
        print("False")
    else:
        ModArray .pop(0)
        i = 0
        j = len(ModArray) - 1
        ModArray .sort()
        Sum = Sum // 2
        while (i <= j):
            s = ModArray[i] + ModArray[j]
            if (s == Sum):
                i1 = i
                i2 = j
                print("True")
                break
            elif (s > Sum):
                j -= 1
            else:
                i += 1


m = 2
a = [1, 3, 9]
n = len(a)
func(n, m, a)

# Expected output:
False
# golomb sequence | print the first n term of golomb sequence ; base cases ; finding and pring first n terms of golomb sequence . ; 
def Golomb(n):
    dp = [0] * (n + 1)
    dp[1] = 1
    print(dp[1], end=" ")
    for i in range(2, n + 1):
        dp[i] = 1 + dp[i - dp[dp[i - 1]]]
        print(dp[i], end=" ")


n = 9
Golomb(n)

# Expected output:
1 2 2 3 3 4 4 4 5
# balanced expressions such that given positions have opening brackets | python 3 code to find number of ways of arranging bracket with proper expressions ; function to calculate the number of proper bracket sequence ; hash array to mark the positions of opening brackets ; dp 2d array ; mark positions in hash array ; first position marked as 1 ; iterate and formulate the recurrences ; if position has a opening bracket ; return answer ; 

N = 1000


def arrangeBraces(n, pos, k):
    h = [False for i in range(N)]
    dp = [[0 for i in range(N)]for i in range(N)]
    for i in range(k):
        h[pos[i]] = 1
    dp[0][0] = 1
    for i in range(1, 2 * n + 1):
        for j in range(2 * n + 1):
            if (h[i]):
                if (j != 0):
                    dp[i][j] = dp[i - 1][j - 1]
                else:
                    dp[i][j] = 0
            else:
                if (j != 0):
                    dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j + 1])
                else:
                    dp[i][j] = dp[i - 1][j + 1]
    return dp[2 * n][0]


n = 3
pos = [2, ]
k = len(pos)
print(arrangeBraces(n, pos, k))

# Expected output:
3
# maximum difference of zeros and ones in binary string | set 2 ( o ( n ) time ) | returns the length of substring with maximum difference of zeroes and ones in binary string ; traverse a binary string from left to right ; add current value to the current_sum according to the character if it ' s ▁ ' 0 ' add 1 else -1 ; update maximum sum ; return - 1 if string does not contain any zero that means all ones otherwise max_sum ; 
def findLength(string, n):
    current_sum = 0
    max_sum = 0
    for i in range(n):
        current_sum += (1 if string[i] == '0'else -1)
        if current_sum < 0:
            current_sum = 0
        max_sum = max(current_sum, max_sum)
    return max_sum if max_sum else 0


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

# Expected output:
6
# number of decimal numbers of length k , that are strict monotone | python3 program to count numbers of k digits that are strictly monotone . ; dp [ i ] [ j ] is going to store monotone numbers of length i + 1 considering j + 1 digits ( 1 , 2 , 3 , . .9 ) ; unit length numbers ; building dp [ ] in bottom up ; 

DP_s = 9


def getNumStrictMonotone(ln):
    DP = [[0] * DP_s for _ in range(ln)]
    for i in range(DP_s):
        DP[0][i] = i + 1
    for i in range(1, ln):
        for j in range(1, DP_s):
            DP[i][j] = DP[i - 1][j - 1] + DP[i][j - 1]
    return DP[ln - 1][DP_s - 1]


print(getNumStrictMonotone(2))

# Expected output:
36
# count ways to divide circle using n non | python code to count ways to divide circle using n non - intersecting chords . ; n = no of points required ; dp array containing the sum ; returning the required number ; 
def chordCnt(A):
    n = 2 * A
    dpArray = [0] * (n + 1)
    dpArray[0] = 1
    dpArray[2] = 1
    for i in range(4, n + 1, 2):
        for j in range(0, i - 1, 2):
            dpArray[i] += (dpArray[j] * dpArray[i - 2 - j])
    return int(dpArray[n])


N = 2
print(chordCnt(N))
N = 1
print(chordCnt(N))
N = 4
print(chordCnt(N))

# Expected output:
2
1
14
# check for possible path in 2d matrix | python3 program to find if there is path from top left to right bottom ; to find the path from top left to bottom right ; set arr [ 0 ] [ 0 ] = 1 ; mark reachable ( from top left ) nodes in first row and first column . ; mark reachable nodes in remaining matrix . ; return yes if right bottom index is 1 ; 

row = 5
col = 5


def isPath(arr):
    arr[0][0] = 1
    for i in range(1, row):
        if (arr[i][0] != -1):
            arr[i][0] = arr[i - 1][0]
    for j in range(1, col):
        if (arr[0][j] != -1):
            arr[0][j] = arr[0][j - 1]
    for i in range(1, row):
        for j in range(1, col):
            if (arr[i][j] != -1):
                arr[i][j] = max(arr[i][j - 1], arr[i - 1][j])
    return (arr[row - 1][col - 1] == 1)


arr = [[0, 0, 0, -1, 0], [-1, 0, 0, -1, -1],
       [0, 0, 0, -1, 0], [-1, 0, -1, 0, -1], [0, 0, -1, 0, 0]]
if (isPath(arr)):
    print("Yes")
else:
    print("No")

# Expected output:
No
# newmanâ €“ shanksâ €“ williams prime | return nth newmanashanksawilliams prime ; base case ; recursive step ; 
def nswp(n):
    if n == 0 or n == 1:
        return 1
    return 2 * nswp(n - 1) + nswp(n - 2)


n = 3
print(nswp(n))

# Expected output:
7
# newman shanks williams prime | return nth newman shanks williams prime ; base case ; finding nth newman shanks williams prime ; 
def nswp(n):
    dp = [1 for x in range(n + 1)]
    for i in range(2, n + 1):
        dp[i] = (2 * dp[i - 1] + dp[i - 2])
    return dp[n]


n = 3
print(nswp(n))

# Expected output:
7
# number of ways to insert a character to increase the lcs by one | python program to number of ways to insert a character to increase lcs by one ; return the number of ways to insert a character to increase the longest common subsequence by one ; insert all positions of all characters in string b ; longest common subsequence ; longest common subsequence from reverse ; inserting character between position i and i + 1 ; 

MAX = 256


def numberofways(A, B, N, M):
    pos = [[]for _ in range(MAX)]
    for i in range(M):
        pos[ord(B[i])].append(i + 1)
    dpl = [[0] * (M + 2)for _ in range(N + 2)]
    for i in range(1, N + 1):
        for j in range(1, M + 1):
            if A[i - 1] == B[j - 1]:
                dpl[i][j] = dpl[i - 1][j - 1] + 1
            else:
                dpl[i][j] = max(dpl[i - 1][j], dpl[i][j - 1])
    LCS = dpl[N][M]
    dpr = [[0] * (M + 2)for _ in range(N + 2)]
    for i in range(N, 0, -1):
        for j in range(M, 0, -1):
            if A[i - 1] == B[j - 1]:
                dpr[i][j] = dpr[i + 1][j + 1] + 1
            else:
                dpr[i][j] = max(dpr[i + 1][j], dpr[i][j + 1])
    ans = 0
    for i in range(N + 1):
        for j in range(MAX):
            for x in pos[j]:
                if dpl[i][x - 1] + dpr[i + 1][x + 1] == LCS:
                    ans += 1
                    break
    return ans


if __name__ == "__main__":
    A = "aa"
    B = "baaa"
    N = len(A)
    M = len(B)
    print(numberofways(A, B, N, M))

# Expected output:
4
# minimum cost to make two strings identical by deleting the digits | function to returns cost of removing the identical characters in 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 cost of removing identical characters in lcs of x [ 0. . i - 1 ] and y [ 0. . j - 1 ] ; if both characters are same , add both of them ; otherwise find the maximum cost among them ; returns cost of making x [ ] and y [ ] identical ; find lcs of x [ ] and y [ ] ; initialize the cost variable ; find cost of all acters in both strings ; 
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] + 2 * (ord(X[i - 1]) - 48)
            else:
                L[i][j] = max(L[i - 1][j], L[i][j - 1])
    return L[m][n]


def findMinCost(X, Y):
    m = len(X)
    n = len(Y)
    cost = 0
    for i in range(m):
        cost += ord(X[i]) - 48
    for i in range(n):
        cost += ord(Y[i]) - 48
    ans = cost - lcs(X, Y, m, n)
    return ans


X = "3759"
Y = "9350"
print("Minimum Cost to make two strings ",
      "identical is = ", findMinCost(X, Y))

# Expected output:
Minimum Cost to make two strings  identical is =  23
# given a large number , check if a subsequence of digits is divisible by 8 | function to calculate any permutation divisible by 8. if such permutation exists , the function will return that permutation else it will return - 1 ; generating all possible permutations and checking if any such permutation is divisible by 8 ; 
def isSubSeqDivisible(st):
    l = len(st)
    arr = [int(ch)for ch in st]
    for i in range(0, l):
        for j in range(i, l):
            for k in range(j, l):
                if (arr[i] % 8 == 0):
                    return True
                elif ((arr[i] * 10 + arr[j]) % 8 == 0 and i != j):
                    return True
                elif ((arr[i] * 100 + arr[j] * 10 + arr[k]) % 8 == 0 and i != j and j != k and i != k):
                    return True
    return False


st = "3144"
if (isSubSeqDivisible(st)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# length of longest balanced subsequence | python3 program to find length of the longest balanced subsequence ; considering all balanced substrings of length 2 ; considering all other substrings ; 
def maxLength(s, n):
    dp = [[0 for i in range(n)]for i in range(n)]
    for i in range(n - 1):
        if (s[i] == '(' and s[i + 1] == ')'):
            dp[i][i + 1] = 2
    for l in range(2, n):
        i = -1
        for j in range(l, n):
            i += 1
            if (s[i] == '(' and s[j] == ')'):
                dp[i][j] = 2 + dp[i + 1][j - 1]
            for k in range(i, j):
                dp[i][j] = max(dp[i][j], dp[i][k] + dp[k + 1][j])
    return dp[0][n - 1]


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

# Expected output:
4
# Maximum sum bitonic subarray | Function to find the maximum sum bitonic subarray . ; to store the maximum sum bitonic subarray ; Find the longest increasing subarray starting at i . ; Now we know that a [ i . . j ] is an increasing subarray . Remove non - positive elements from the left side as much as possible . ; Find the longest decreasing subarray starting at j . ; Now we know that a [ j . . k ] is a decreasing subarray . Remove non - positive elements from the right side as much as possible . last is needed to keep the last seen element . ; Compute the max sum of the increasing part . ; Compute the max sum of the decreasing part . ; The overall max sum is the sum of both parts minus the peak element , because it was counted twice . ; If the next element is equal to the current , i . e . arr [ i + 1 ] == arr [ i ] , last == i . To ensure the algorithm has progress , get the max of last and i + 1. ; required maximum sum ; The example from the article , the answer is 19. ; Always increasing , the answer is 15. ; Always decreasing , the answer is 15. ; All are equal , the answer is 5. ; The whole array is bitonic , but the answer is 7. ; The answer is 4 ( the tail ) .
def maxSumBitonicSubArr(arr, n):
    max_sum = -10 ** 9
    i = 0
    while (i < n):
        j = i
        while (j + 1 < n and arr[j] < arr[j + 1]):
            j += 1
        while (i < j and arr[i] <= 0):
            i += 1
        k = j
        while (k + 1 < n and arr[k] > arr[k + 1]):
            k += 1
        last = k
        while (k > j and arr[k] <= 0):
            k -= 1
        nn = arr[i:j + 1]
        sum_inc = sum(nn)
        nn = arr[j:k + 1]
        sum_dec = sum(nn)
        sum_all = sum_inc + sum_dec - arr[j]
        max_sum = max([max_sum, sum_inc, sum_dec, sum_all])
        i = max(last, i + 1)
    return max_sum


arr = [5, 3, 9, 2, 7, 6, 4]
n = len(arr)
print("Maximum Sum = ", maxSumBitonicSubArr(arr, n))
arr2 = [1, 2, 3, 4, 5]
n2 = len(arr2)
print("Maximum Sum = ", maxSumBitonicSubArr(arr2, n2))
arr3 = [5, 4, 3, 2, 1]
n3 = len(arr3)
print("Maximum Sum = ", maxSumBitonicSubArr(arr3, n3))
arr4 = [5, 5, 5, 5]
n4 = len(arr4)
print("Maximum Sum = ", maxSumBitonicSubArr(arr4, n4))
arr5 = [-1, 0, 1, 2, 3, 1, 0, -1, -10]
n5 = len(arr5)
print("Maximum Sum = ", maxSumBitonicSubArr(arr5, n5))
arr6 = [-1, 0, 1, 2, 0, -1, -2, 0, 1, 3]
n6 = len(arr6)
print("Maximum Sum = ", maxSumBitonicSubArr(arr6, n6))

# Expected output:
Maximum Sum =  19
Maximum Sum =  15
Maximum Sum =  15
Maximum Sum =  5
Maximum Sum =  7
Maximum Sum =  4
# smallest sum contiguous subarray | python program to find the smallest sum contiguous subarray ; function to find the smallest sum contiguous subarray ; to store the minimum value that is ending up to the current index ; to store the minimum value encountered so far ; traverse the array elements ; if min_ending_here > 0 , then it could not possibly contribute to the minimum sum further ; else add the value arr [ i ] to min_ending_here ; update min_so_far ; required smallest sum contiguous subarray value ; 

import sys


def smallestSumSubarr(arr, n):
    min_ending_here = sys .maxsize
    min_so_far = sys .maxsize
    for i in range(n):
        if (min_ending_here > 0):
            min_ending_here = arr[i]
        else:
            min_ending_here += arr[i]
        min_so_far = min(min_so_far, min_ending_here)
    return min_so_far


arr = [3, -4, 2, -3, -1, 7, -5]
n = len(arr)
print("Smallest sum: ", smallestSumSubarr(arr, n))

# Expected output:
Smallest sum:  -6
# n | python3 code to find nth number with digits 0 , 1 , 2 , 3 , 4 , 5 ; if the number is less than 6 return the number as it is . ; call the function again and again the get the desired result . and convert the number to base 6. ; decrease the number by 1 and call ans function to convert n to base 6 ; 
def ans(n):
    if (n < 6):
        return n
    return n % 6 + 10 * (ans(n // 6)) - 1


def getSpecialNumber(N):
    return ans(N)


if __name__ == '__main__':
    N = 17
    answer = getSpecialNumber(N)
    print(answer)

# Expected output:
24