giulio98/xlcost-single-prompt huggingface dataset:
# longest bitonic subsequence | dp | lbs ( ) returns the length of the longest bitonic subsequence in arr [ ] of size n . the function mainly creates two temporary arrays lis [ ] and lds [ ] and returns the maximum lis [ i ] + lds [ i ] - 1. lis [ i ] == > longest increasing subsequence ending with arr [ i ] lds [ i ] == > longest decreasing subsequence starting with arr [ i ] ; allocate memory for lis [ ] and initialize lis values as 1 for all indexes ; compute lis values from left to right ; allocate memory for lds and initialize lds values for all indexes ; compute lds values from right to left ; return the maximum value of ( lis [ i ] + lds [ i ] - 1 ) ; 
def lbs(arr):
    n = len(arr)
    lis = [1 for i in range(n + 1)]
    for i in range(1, n):
        for j in range(0, i):
            if ((arr[i] > arr[j]) and (lis[i] < lis[j] + 1)):
                lis[i] = lis[j] + 1
    lds = [1 for i in range(n + 1)]
    for i in reversed(range(n - 1)):
        for j in reversed(range(i - 1, n)):
            if (arr[i] > arr[j] and lds[i] < lds[j] + 1):
                lds[i] = lds[j] + 1
    maximum = lis[0] + lds[0] - 1
    for i in range(1, n):
        maximum = max((lis[i] + lds[i] - 1), maximum)
    return maximum


arr = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]
print("Length of LBS is", lbs(arr))

# Expected output:
Length of LBS is 7
# palindrome partitioning | dp | mincut function ; 
def minCut(a):
    cut = [0 for i in range(len(a))]
    palindrome = [[False for i in range(len(a))]for j in range(len(a))]
    for i in range(len(a)):
        minCut = i
        for j in range(i + 1):
            if (a[i] == a[j] and (i - j < 2 or palindrome[j + 1][i - 1])):
                palindrome[j][i] = True
                minCut = min(minCut, 0 if j == 0 else (cut[j - 1] + 1))
        cut[i] = minCut
    return cut[len(a) - 1]


if __name__ == '__main__':
    print(minCut("aab"))
    print(minCut("aabababaxx"))

# Expected output:
1
2
# palindrome partitioning | dp | using memoizatoin to solve the partition problem . function to check if input string is pallindrome or not ; using two pointer technique to check pallindrome ; function to find keys for the hashmap ; returns the minimum number of cuts needed to partition a string such that every part is a palindrome ; key for the input string ; if the no of partitions for string " ij " is already calculated then return the calculated value using the hashmap ; every string of length 1 is a pallindrome ; make a cut at every possible location starting from i to j ; if left cut is found already ; if right cut is found already ; recursively calculating for left and right strings ; taking minimum of all k possible cuts ; return the min cut value for complete string . ; 
def ispallindrome(input, start, end):
    while (start < end):
        if (input[start] != input[end]):
            return False
        start += 1
        end -= 1
    return True


def convert(a, b):
    return str(a) + str(b)


def minpalparti_memo(input, i, j, memo):
    if (i > j):
        return 0
    ij = convert(i, j)
    if (ij in memo):
        return memo[ij]
    if (i == j):
        memo[ij] = 0
        return 0
    if (ispallindrome(input, i, j)):
        memo[ij] = 0
        return 0
    minimum = 1000000000
    for k in range(i, j):
        left_min = 1000000000
        right_min = 1000000000
        left = convert(i, k)
        right = convert(k + 1, j)
        if (left in memo):
            left_min = memo[left]
        if (right in memo):
            right_min = memo[right]
        if (left_min == 1000000000):
            left_min = minpalparti_memo(input, i, k, memo)
        if (right_min == 1000000000):
            right_min = minpalparti_memo(input, k + 1, j, memo)
        minimum = min(minimum, left_min + 1 + right_min)
    memo[ij] = minimum
    return memo[ij]


if __name__ == '__main__':
    input = "ababbbabbababa"
    memo = dict()
    print(minpalparti_memo(input, 0, len(input) - 1, memo))

# Expected output:
3
# word wrap problem | dp | a dynamic programming solution for word wrap problem ; a utility function to print the solution ; l [ ] represents lengths of different words in input sequence . for example , l [ ] = { 3 , 2 , 2 , 5 } is for a sentence like " aaa ▁ bb ▁ cc ▁ ddddd " . n is size of l [ ] and m is line width ( maximum no . of characters that can fit in a line ) ; for simplicity , 1 extra space is used in all below arrays extras [ i ] [ j ] will have number of extra spaces if words from i to j are put in a single line ; lc [ i ] [ j ] will have cost of a line which has words from i to j ; c [ i ] will have total cost of optimal arrangement of words from 1 to i ; p [ ] is used to print the solution . ; calculate extra spaces in a single line . the value extra [ i ] [ j ] indicates extra spaces if words from word number i to j are placed in a single line ; calculate line cost corresponding to the above calculated extra spaces . the value lc [ i ] [ j ] indicates cost of putting words from word number i to j in a single line ; calculate minimum cost and find minimum cost arrangement . the value c [ j ] indicates optimized cost to arrange words from word number 1 to j . ; 

INF = 2147483647


def printSolution(p, n):
    k = 0
    if p[n] == 1:
        k = 1
    else:
        k = printSolution(p, p[n] - 1) + 1
    print('Line number ', k, ': From word no. ', p[n], 'to ', n)
    return k


def solveWordWrap(l, n, M):
    extras = [[0 for i in range(n + 1)]for i in range(n + 1)]
    lc = [[0 for i in range(n + 1)]for i in range(n + 1)]
    c = [0 for i in range(n + 1)]
    p = [0 for i in range(n + 1)]
    for i in range(n + 1):
        extras[i][i] = M - l[i - 1]
        for j in range(i + 1, n + 1):
            extras[i][j] = (extras[i][j - 1] - l[j - 1] - 1)
    for i in range(n + 1):
        for j in range(i, n + 1):
            if extras[i][j] < 0:
                lc[i][j] = INF
            elif j == n and extras[i][j] >= 0:
                lc[i][j] = 0
            else:
                lc[i][j] = (extras[i][j] * extras[i][j])
    c[0] = 0
    for j in range(1, n + 1):
        c[j] = INF
        for i in range(1, j + 1):
            if (c[i - 1] != INF and lc[i][j] !=
                    INF and ((c[i - 1] + lc[i][j]) < c[j])):
                c[j] = c[i - 1] + lc[i][j]
                p[j] = i
    printSolution(p, n)


l = [3, 2, 2, 5]
n = len(l)
M = 6
solveWordWrap(l, n, M)

# Expected output:
Line number  1 : From word no.  1 to  1
Line number  2 : From word no.  2 to  3
Line number  3 : From word no.  4 to  4
# ugly numbers | this function divides a by greatest divisible power of b ; function to check if a number is ugly or not ; function to get the nth ugly number ; ugly number count ; check for all integers untill ugly count becomes n ; 
def maxDivide(a, b):
    while a % b == 0:
        a = a / b
    return a


def isUgly(no):
    no = maxDivide(no, 2)
    no = maxDivide(no, 3)
    no = maxDivide(no, 5)
    return 1 if no == 1 else 0


def getNthUglyNo(n):
    i = 1
    count = 1
    while n > count:
        i += 1
        if isUgly(i):
            count += 1
    return i


no = getNthUglyNo(150)
print("150th ugly no. is ", no)

# Expected output:
150th ugly no. is  5832
# longest palindromic substring | set 1 | function to pra substring str [ low . . high ] ; this function prints the longest palindrome substring it also returns the length of the longest palindrome ; get length of input string ; all substrings of length 1 are palindromes ; nested loop to mark start and end index ; check palindrome ; palindrome ; return length of lps ; 
def printSubStr(str, low, high):
    for i in range(low, high + 1):
        print(str[i], end="")


def longestPalSubstr(str):
    n = len(str)
    maxLength = 1
    start = 0
    for i in range(n):
        for j in range(i, n):
            flag = 1
            for k in range(0, ((j - i) // 2) + 1):
                if (str[i + k] != str[j - k]):
                    flag = 0
            if (flag != 0 and (j - i + 1) > maxLength):
                start = i
                maxLength = j - i + 1
    print("Longest palindrome subString is: ", end="")
    printSubStr(str, start, start + maxLength - 1)
    return maxLength


if __name__ == '__main__':
    str = "forgeeksskeegfor"
    print("Lengthis:", longestPalSubstr(str))

# Expected output:
Longest palindrome subString is: geeksskeegLengthis: 10
# longest palindromic substring | set 1 | python program ; a utility function to print a substring str [ low . . high ] ; this function prints the longest palindrome substring of st [ ] . it also returns the length of the longest palindrome ; get length of input string ; table [ i ] [ j ] will be false if substring str [ i . . j ] is not palindrome . else table [ i ] [ j ] will be true ; all substrings of length 1 are palindromes ; check for sub - string of length 2. ; check for lengths greater than 2. k is length of substring ; fix the starting index ; get the ending index of substring from starting index i and length k ; checking for sub - string from ith index to jth index iff st [ i + 1 ] to st [ ( j - 1 ) ] is a palindrome ; return length of lps ; 

import sys


def printSubStr(st, low, high):
    sys .stdout .write(st[low:high + 1])
    sys .stdout .flush()
    return ''


def longestPalSubstr(st):
    n = len(st)
    table = [[0 for x in range(n)]for y in range(n)]
    maxLength = 1
    i = 0
    while (i < n):
        table[i][i] = True
        i = i + 1
    start = 0
    i = 0
    while i < n - 1:
        if (st[i] == st[i + 1]):
            table[i][i + 1] = True
            start = i
            maxLength = 2
        i = i + 1
    k = 3
    while k <= n:
        i = 0
        while i < (n - k + 1):
            j = i + k - 1
            if (table[i + 1][j - 1] and st[i] == st[j]):
                table[i][j] = True
                if (k > maxLength):
                    start = i
                    maxLength = k
            i = i + 1
        k = k + 1
    print("Longest palindrome substring is: ",
          printSubStr(st, start, start + maxLength - 1))
    return maxLength


st = "forgeeksskeegfor"
l = longestPalSubstr(st)
print("Length is:", l)

# Expected output:
geeksskeegLongest palindrome substring is:  
Length is: 10
# optimal binary search tree | dp | a utility function to get sum of array elements freq [ i ] to freq [ j ] ; a recursive function to calculate cost of optimal binary search tree ; base cases no elements in this subarray ; one element in this subarray ; get sum of freq [ i ] , freq [ i + 1 ] , ... freq [ j ] ; initialize minimum value ; one by one consider all elements as root and recursively find cost of the bst , compare the cost with min and update min if needed ; return minimum value ; the main function that calculates minimum cost of a binary search tree . it mainly uses optcost ( ) to find the optimal cost . ; here array keys [ ] is assumed to be sorted in increasing order . if keys [ ] is not sorted , then add code to sort keys , and rearrange freq [ ] accordingly . ; 
def Sum(freq, i, j):
    s = 0
    for k in range(i, j + 1):
        s += freq[k]
    return s


def optCost(freq, i, j):
    if j < i:
        return 0
    if j == i:
        return freq[i]
    fsum = Sum(freq, i, j)
    Min = 999999999999
    for r in range(i, j + 1):
        cost = (optCost(freq, i, r - 1) + optCost(freq, r + 1, j))
        if cost < Min:
            Min = cost
    return Min + fsum


def optimalSearchTree(keys, freq, n):
    return optCost(freq, 0, n - 1)


if __name__ == '__main__':
    keys = [10, 12, 20]
    freq = [34, 8, 50]
    n = len(keys)
    print("Cost of Optimal BST is", optimalSearchTree(keys, freq, n))

# Expected output:
Cost of Optimal BST is 142
# optimal binary search tree | dp | dynamic programming code for optimal binary search tree problem ; a utility function to get sum of array elements freq [ i ] to freq [ j ] ; a dynamic programming based function that calculates minimum cost of a binary search tree . ; create an auxiliary 2d matrix to store results of subproblems ; for a single key , cost is equal to frequency of the key ; now we need to consider chains of length 2 , 3 , ... . l is chain length . ; i is row number in cost ; get column number j from row number i and chain length l ; try making all keys in interval keys [ i . . j ] as root ; c = cost when keys [ r ] becomes root of this subtree ; 

INT_MAX = 2147483647


def sum(freq, i, j):
    s = 0
    for k in range(i, j + 1):
        s += freq[k]
    return s


def optimalSearchTree(keys, freq, n):
    cost = [[0 for x in range(n)]for y in range(n)]
    for i in range(n):
        cost[i][i] = freq[i]
    for L in range(2, n + 1):
        for i in range(n - L + 2):
            j = i + L - 1
            if i >= n or j >= n:
                break
            cost[i][j] = INT_MAX
            for r in range(i, j + 1):
                c = 0
                if (r > i):
                    c += cost[i][r - 1]
                if (r < j):
                    c += cost[r + 1][j]
                c += sum(freq, i, j)
                if (c < cost[i][j]):
                    cost[i][j] = c
    return cost[0][n - 1]


if __name__ == '__main__':
    keys = [10, 12, 20]
    freq = [34, 8, 50]
    n = len(keys)
    print("Cost of Optimal BST is", optimalSearchTree(keys, freq, n))

# Expected output:
Cost of Optimal BST is 142
# boolean parenthesization problem | dp | returns count of all possible parenthesizations that lead to result true for a boolean expression with symbols like true and false and operators like & , | and ^ filled between symbols ; fill diaginal entries first all diagonal entries in t [ i ] [ i ] are 1 if symbol [ i ] is t ( true ) . similarly , all f [ i ] [ i ] entries are 1 if symbol [ i ] is f ( false ) ; now fill t [ i ] [ i + 1 ] , t [ i ] [ i + 2 ] , t [ i ] [ i + 3 ] ... in order and f [ i ] [ i + 1 ] , f [ i ] [ i + 2 ] , f [ i ] [ i + 3 ] ... in order ; find place of parenthesization using current value of gap ; store total [ i ] [ k ] and total [ k + 1 ] [ j ] ; follow the recursive formulas according to the current operator ; 
def countParenth(symb, oper, n):
    F = [[0 for i in range(n + 1)]for i in range(n + 1)]
    T = [[0 for i in range(n + 1)]for i in range(n + 1)]
    for i in range(n):
        if symb[i] == 'F':
            F[i][i] = 1
        else:
            F[i][i] = 0
        if symb[i] == 'T':
            T[i][i] = 1
        else:
            T[i][i] = 0
    for gap in range(1, n):
        i = 0
        for j in range(gap, n):
            T[i][j] = F[i][j] = 0
            for g in range(gap):
                k = i + g
                tik = T[i][k] + F[i][k]
                tkj = T[k + 1][j] + F[k + 1][j]
                if oper[k] == '&':
                    T[i][j] += T[i][k] * T[k + 1][j]
                    F[i][j] += (tik * tkj - T[i][k] * T[k + 1][j])
                if oper[k] == '|':
                    F[i][j] += F[i][k] * F[k + 1][j]
                    T[i][j] += (tik * tkj - F[i][k] * F[k + 1][j])
                if oper[k] == '^':
                    T[i][j] += (F[i][k] * T[k + 1][j] + T[i][k] * F[k + 1][j])
                    F[i][j] += (T[i][k] * T[k + 1][j] + F[i][k] * F[k + 1][j])
            i += 1
    return T[0][n - 1]


symbols = "TTFT"
operators = "|&^"
n = len(symbols)
print(countParenth(symbols, operators, n))

# Expected output:
4
# boolean parenthesization problem | dp | countways function ; base condition ; count number of true in left partition ; count number of false in left partition ; count number of true in right partition ; count number of false in right partition ; evaluate and operation ; evaluate or operation ; evaluate xor operation ; 
def countParenth(symb, oper, n):
    F = [[0 for i in range(n + 1)]
         for i in range(n + 1)]
    T = [[0 for i in range(n + 1)]
         for i in range(n + 1)]
    for i in range(n):
        if symb[i] == 'F':
            F[i][i] = 1
        else:
            F[i][i] = 0

        if symb[i] == 'T':
            T[i][i] = 1
        else:
            T[i][i] = 0
    for gap in range(1, n):
        i = 0
        for j in range(gap, n):
            T[i][j] = F[i][j] = 0
            for g in range(gap):
                k = i + g
                tik = T[i][k] + F[i][k]
                tkj = T[k + 1][j] + F[k + 1][j]
                if oper[k] == '&':
                    T[i][j] += T[i][k] * T[k + 1][j]
                    F[i][j] += (tik * tkj - T[i][k] *
                                T[k + 1][j])
                if oper[k] == '|':
                    F[i][j] += F[i][k] * F[k + 1][j]
                    T[i][j] += (tik * tkj - F[i][k] *
                                F[k + 1][j])
                if oper[k] == '^':
                    T[i][j] += (F[i][k] * T[k + 1][j] +
                                T[i][k] * F[k + 1][j])
                    F[i][j] += (T[i][k] * T[k + 1][j] +
                                F[i][k] * F[k + 1][j])
            i += 1
    return T[0][n - 1]


symbols = "TTFT"
operators = "|&^"
n = len(symbols)
print(countParenth(symbols, operators, n))

# Expected output:
4
# mobile numeric keypad problem | return count of all possible numbers of length n in a given numeric keyboard ; left , up , right , down move from current location ; taking n + 1 for simplicity - count [ i ] [ j ] will store number count starting with digit i and length j count [ 10 ] [ n + 1 ] ; count numbers starting with digit i and of lengths 0 and 1 ; bottom up - get number count of length 2 , 3 , 4 , ... , n ; loop on keypad row ; loop on keypad column ; process for 0 to 9 digits ; here we are counting the numbers starting with digit keypad [ i ] [ j ] and of length k keypad [ i ] [ j ] will become 1 st digit , and we need to look for ( k - 1 ) more digits ; move left , up , right , down from current location and if new location is valid , then get number count of length ( k - 1 ) from that new digit and add in count we found so far ; get count of all possible numbers of length " n " starting with digit 0 , 1 , 2 , ... , 9 ; 
def getCount(keypad, n):
    if (keypad is None or n <= 0):
        return 0
    if (n == 1):
        return 10
    row = [0, 0, -1, 0, 1]
    col = [0, -1, 0, 1, 0]
    count = [[0] * (n + 1)] * 10
    i = 0
    j = 0
    k = 0
    move = 0
    ro = 0
    co = 0
    num = 0
    nextNum = 0
    totalCount = 0
    for i in range(10):
        count[i][0] = 0
        count[i][1] = 1
    for k in range(2, n + 1):
        for i in range(4):
            for j in range(3):
                if (keypad[i][j] != '*' and keypad[i][j] != '#'):
                    num = ord(keypad[i][j]) - 48
                    count[num][k] = 0
                    for move in range(5):
                        ro = i + row[move]
                        co = j + col[move]
                        if (ro >= 0 and ro <= 3 and co >= 0 and co <=
                                2 and keypad[ro][co] != '*' and keypad[ro][co] != '#'):
                            nextNum = ord(keypad[ro][co]) - 48
                            count[num][k] += count[nextNum][k - 1]
    totalCount = 0
    for i in range(10):
        totalCount += count[i][n]
    return totalCount


if __name__ == "__main__":
    keypad = [['1', '2', '3'], ['4', '5', '6'],
              ['7', '8', '9'], ['*', '0', '#']]
    print("Count for numbers of length", 1, ":", getCount(keypad, 1))
    print("Count for numbers of length", 2, ":", getCount(keypad, 2))
    print("Count for numbers of length", 3, ":", getCount(keypad, 3))
    print("Count for numbers of length", 4, ":", getCount(keypad, 4))
    print("Count for numbers of length", 5, ":", getCount(keypad, 5))

# Expected output:
Count for numbers of length 1 : 10
Count for numbers of length 2 : 20
Count for numbers of length 3 : 40
Count for numbers of length 4 : 80
Count for numbers of length 5 : 160
# mobile numeric keypad problem | return count of all possible numbers of length n in a given numeric keyboard ; odd [ i ] , even [ i ] arrays represent count of numbers starting with digit i for any length j ; for j = 1 ; bottom up calculation from j = 2 to n ; here we are explicitly writing lines for each number 0 to 9. but it can always be written as dfs on 4 x3 grid using row , column array valid moves ; get count of all possible numbers of length " n " starting with digit 0 , 1 , 2 , ... , 9 ; 
def getCount(keypad, n):
    if (not keypad or n <= 0):
        return 0
    if (n == 1):
        return 10
    odd = [0] * 10
    even = [0] * 10
    i = 0
    j = 0
    useOdd = 0
    totalCount = 0
    for i in range(10):
        odd[i] = 1
    for j in range(2, n + 1):
        useOdd = 1 - useOdd
        if (useOdd == 1):
            even[0] = odd[0] + odd[8]
            even[1] = odd[1] + odd[2] + odd[4]
            even[2] = odd[2] + odd[1] + odd[3] + odd[5]
            even[3] = odd[3] + odd[2] + odd[6]
            even[4] = odd[4] + odd[1] + odd[5] + odd[7]
            even[5] = odd[5] + odd[2] + odd[4] + odd[8] + odd[6]
            even[6] = odd[6] + odd[3] + odd[5] + odd[9]
            even[7] = odd[7] + odd[4] + odd[8]
            even[8] = odd[8] + odd[0] + odd[5] + odd[7] + odd[9]
            even[9] = odd[9] + odd[6] + odd[8]
        else:
            odd[0] = even[0] + even[8]
            odd[1] = even[1] + even[2] + even[4]
            odd[2] = even[2] + even[1] + even[3] + even[5]
            odd[3] = even[3] + even[2] + even[6]
            odd[4] = even[4] + even[1] + even[5] + even[7]
            odd[5] = even[5] + even[2] + even[4] + even[8] + even[6]
            odd[6] = even[6] + even[3] + even[5] + even[9]
            odd[7] = even[7] + even[4] + even[8]
            odd[8] = even[8] + even[0] + even[5] + even[7] + even[9]
            odd[9] = even[9] + even[6] + even[8]
    totalCount = 0
    if (useOdd == 1):
        for i in range(10):
            totalCount += even[i]
    else:
        for i in range(10):
            totalCount += odd[i]
    return totalCount


if __name__ == "__main__":
    keypad = [['1', '2', '3'], ['4', '5', '6'],
              ['7', '8', '9'], ['*', '0', '#']]
    print("Count for numbers of length ", 1, ": ", getCount(keypad, 1))
    print("Count for numbers of length ", 2, ": ", getCount(keypad, 2))
    print("Count for numbers of length ", 3, ": ", getCount(keypad, 3))
    print("Count for numbers of length ", 4, ": ", getCount(keypad, 4))
    print("Count for numbers of length ", 5, ": ", getCount(keypad, 5))

# Expected output:
Count for numbers of length  1 :  10
Count for numbers of length  2 :  36
Count for numbers of length  3 :  138
Count for numbers of length  4 :  532
Count for numbers of length  5 :  2062
# count of n digit numbers whose sum of digits equals to given sum | recursive function to count ' n ' digit numbers with sum of digits as ' sum ' this function considers leading 0 's also as digits, that is why not directly called ; base case ; initialize answer ; traverse through every digit and count numbers beginning with it using recursion ; this is mainly a wrapper over countrec . it explicitly handles leading digit and calls countrec ( ) for remaining digits . ; initialize final answer ; traverse through every digit from 1 to 9 and count numbers beginning with it ; 
def countRec(n, sum):
    if (n == 0):
        return (sum == 0)
    if (sum == 0):
        return 1
    ans = 0
    for i in range(0, 10):
        if (sum - i >= 0):
            ans = ans + countRec(n - 1, sum - i)
    return ans


def finalCount(n, sum):
    ans = 0
    for i in range(1, 10):
        if (sum - i >= 0):
            ans = ans + countRec(n - 1, sum - i)
    return ans


n = 2
sum = 5
print(finalCount(n, sum))

# Expected output:
5