giulio98/xlcost-single-prompt huggingface dataset:
# word wrap problem | dp | 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 ) ; 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 ) ; 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
# palindrome partitioning | dp | python code for implementation of naive recursive approach ; 
def isPalindrome(x):
    return x == x[::-1]


def minPalPartion(string, i, j):
    if i >= j or isPalindrome(string[i:j + 1]):
        return 0
    ans = float('inf')
    for k in range(i, j):
        count = (
            1 +
            minPalPartion(
                string,
                i,
                k) +
            minPalPartion(
                string,
                k +
                1,
                j))
        ans = min(ans, count)
    return ans


def main():
    string = "ababbbabbababa"
    print("Min cuts needed for Palindrome Partitioning is ",
          minPalPartion(string, 0, len(string) - 1),)


if __name__ == "__main__":
    main()

# Expected output:
Min cuts needed for Palindrome Partitioning is  3
# palindrome partitioning | dp | 
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 | 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
# 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 for i in reversed ( range ( n - 1 ) ) : loop from n - 2 downto 0 for j in reversed ( range ( i - 1 , n ) ) : loop from n - 1 downto i - 1 ; 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)]
    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
# egg dropping puzzle | dp | a dynamic programming based python program for the egg dropping puzzle ; function to get minimum number of trials needed in worst case with n eggs and k floors ; a 2d table where entry eggfloor [ i ] [ j ] will represent minimum number of trials needed for i eggs and j floors . ; we need one trial for one floor and0 trials for 0 floors ; we always need j trials for one egg and j floors . ; fill rest of the entries in table using optimal substructure property ; eggfloor [ n ] [ k ] holds the result ; 

INT_MAX = 32767


def eggDrop(n, k):
    eggFloor = [[0 for x in range(k + 1)]for x in range(n + 1)]
    for i in range(1, n + 1):
        eggFloor[i][1] = 1
        eggFloor[i][0] = 0
    for j in range(1, k + 1):
        eggFloor[1][j] = j
    for i in range(2, n + 1):
        for j in range(2, k + 1):
            eggFloor[i][j] = INT_MAX
            for x in range(1, j + 1):
                res = 1 + max(eggFloor[i - 1][x - 1], eggFloor[i][j - x])
                if res < eggFloor[i][j]:
                    eggFloor[i][j] = res
    return eggFloor[n][k]


n = 2
k = 36
print("Minimum number of trials in worst case with" + str(n) +
      "eggs and " + str(k) + " floors is " + str(eggDrop(n, k)))

# Expected output:
Minimum number of trials in worst case with2eggs and 36 floors is 8
# 0 | returns the maximum value that can be put in a knapsack of capacity w ; base case ; if weight of the nth item is more than knapsack of capacity w , then this item cannot be included in the optimal solution ; return the maximum of two cases : ( 1 ) nth item included ( 2 ) not included ; 
def knapSack(W, wt, val, n):
    if n == 0 or W == 0:
        return 0
    if (wt[n - 1] > W):
        return knapSack(W, wt, val, n - 1)
    else:
        return max(val[n - 1] + knapSack(W - wt[n - 1], wt,
                   val, n - 1), knapSack(W, wt, val, n - 1))


val = [60, 100, 120]
wt = [10, 20, 30]
W = 50
n = len(val)
print(knapSack(W, wt, val, n))

# Expected output:
220
# min cost path | dp | python3 program for the above approach ; for 1 st column ; for 1 st row ; for rest of the 2d matrix ; returning the value in last cell ; 
def minCost(cost, row, col):
    for i in range(1, row):
        cost[i][0] += cost[i - 1][0]
    for j in range(1, col):
        cost[0][j] += cost[0][j - 1]
    for i in range(1, row):
        for j in range(1, col):
            cost[i][j] += (min(cost[i - 1][j - 1],
                           min(cost[i - 1][j], cost[i][j - 1])))
    return cost[row - 1][col - 1]


if __name__ == '__main__':
    row = 3
    col = 3
    cost = [[1, 2, 3], [4, 8, 2], [1, 5, 3]]
    print(minCost(cost, row, col))

# Expected output:
8
# longest increasing subsequence | dp | to make use of recursive calls , this function must return two things : 1 ) length of lis ending with element arr [ n - 1 ] . we use max_ending_here for this purpose 2 ) overall maximum as the lis may end with an element before arr [ n - 1 ] max_ref is used this purpose . the value of lis of full array of size n is stored in * max_ref which is our final result ; base case ; maxendinghere is the length of lis ending with arr [ n - 1 ] ; recursively get all lis ending with arr [ 0 ] , arr [ 1 ] . . arr [ n - 2 ] if arr [ n - 1 ] is maller than arr [ n - 1 ] , and max ending with arr [ n - 1 ] needs to be updated , then update it ; compare maxendinghere with overall maximum . and update the overall maximum if needed ; return length of lis ending with arr [ n - 1 ] ; the wrapper function for _lis ( ) ; maximum variable holds the result ; the function _lis ( ) stores its result in maximum ; returns max ; 

global maximum


def _lis(arr, n):
    global maximum
    if n == 1:
        return 1
    maxEndingHere = 1
    for i in range(1, n):
        res = _lis(arr, i)
        if arr[i-1] < arr[n-1] and res+1 > maxEndingHere:
            maxEndingHere = res + 1
    maximum = max(maximum, maxEndingHere)

    return maxEndingHere


def lis(arr):
    global maximum
    n = len(arr)
    maximum = 1
    _lis(arr, n)

    return maximum


arr = [10, 22, 9, 33, 21, 50, 41, 60]
n = len(arr)
print("Length of lis is ", lis(arr))

# Expected output:
Length of lis is  5
# find all numbers in range [ 1 , n ] that are not present in given array | function to find the missing numbers ; traverse the array arr [ ] ; update ; traverse the array arr [ ] ; if num is not present ; 
def getMissingNumbers(arr):
    for num in arr:
        arr[abs(num) - 1] = -(abs(arr[abs(num) - 1]))
    for pos, num in enumerate(arr):
        if num > 0:
            print(pos + 1, end=' ')


arr = [5, 5, 4, 4, 2]
getMissingNumbers(arr)

# Expected output:
1 3
# find the kth smallest odd length palindrome number | function to find the kth smallest odd length palindrome number ; store the original number k ; removing the last digit of k ; generate the palindrome by appending the reverse of k except last digit to itself ; find the remainder ; add the digit to palin ; divide k by 10 ; return the resultant palindromic number formed ; 
def oddLengthPalindrome(K):
    palin = K
    K = K // 10
    while (K > 0):
        rev = K % 10
        palin = palin * 10 + rev
        K = K // 10
    return palin


if __name__ == '__main__':
    K = 504
    print(oddLengthPalindrome(K))

# Expected output:
50405
# maximize length of subsequence consisting of single distinct character possible by k increments in a string | function to find the maximum length of a subsequence of same characters after at most k increment operations ; store the size of s ; sort temparray ; stores the maximum length and the sum of the sliding window ; traverse the s ; add the current character to the window ; decrease the window size ; update the value of sum ; increment the value of start ; update the maximum window size ; print the resultant maximum length of the subsequence ; 
def maxSubsequenceLen(S, K):
    N = len(S)
    start, end = 0, 0
    S = sorted(S)
    ans, sum = -10 ** 9, 0
    for end in range(N):
        sum = sum + (ord(S[end]) - ord('a'))
        while (sum + K < (ord(S[end]) - ord('a')) * (end - start + 1)):
            sum = sum - (ord(S[start]) - ord('a'))
            start += 1
        ans = max(ans, end - start + 1)
    print(ans)


if __name__ == '__main__':
    S = "acscbcca"
    K = 1
    maxSubsequenceLen(S, K)

# Expected output:
5
# check if a given integer is the product of k consecutive integers | function to check if n can be expressed as the product of k consecutive integers ; stores the k - th root of n ; stores the product of k consecutive integers ; traverse over the range [ 1 , k ] ; update the product ; if product is n , then return " yes " ; otherwise , traverse over the range [ 2 , kthroot ] ; update the value of product ; if product is equal to n ; otherwise , return " no " ; 
def checkPro(n, k):
    KthRoot = int(n ** (1 / k))
    product = 1
    for i in range(1, k + 1):
        product = product * i
    print(product)
    if (product == N):
        return ("Yes")
    for i in range(2, KthRoot + 1):
        product = product * (i + k - 1)
        product = product / (i - 1)
        print(product)
        if (product == N):
            return ("Yes")
    return ("No")


N = 210
K = 3
print(checkPro(N, K))

# Expected output:
6
24.0
60.0
120.0
210.0
Yes
# count possible removals to make absolute difference between the sum of odd and even indexed elements equal to k | function to check if difference between the sum of odd and even indexed elements after removing the first element is k or not ; stores the sum of elements at odd and even indices ; return 1 if difference is k ; function to check if difference between the sum of odd and even indexed elements after removing the second element is k or not ; stores the sum of elements at odd and even indices ; return 1 if difference is k ; function to count number of elements to be removed to make sum of differences between odd and even indexed elements equal to k ; size of given array ; base conditions ; stores prefix and suffix sums ; base assignments ; store prefix sums of even indexed elements ; store prefix sums of odd indexed elements ; similarly , store suffix sums of elements at even and odd indices ; stores the count of possible removals ; traverse and remove the ith element ; if the current element is excluded , then previous index ( i - 1 ) points to ( i + 2 ) and ( i - 2 ) points to ( i + 1 ) ; find count when 0 th element is removed ; find count when 1 st element is removed ; count gives the required answer ; 
def findCount0th(arr, N, K):
    oddsum = 0
    evensum = 0
    for i in range(1, N, 2):
        oddsum += arr[i]
    for i in range(2, N, 2):
        evensum += arr[i]
    if (abs(oddsum - evensum) == K):
        return 1
    else:
        return 0


def findCount1st(arr, N, K):
    evensum = arr[0]
    oddsum = 0
    for i in range(3, N, 2):
        evensum += arr[i]
    for i in range(2, N, 2):
        oddsum += arr[i]
    if (abs(oddsum - evensum) == K):
        return 1
    else:
        return 0


def countTimes(arr, K):
    N = len(arr)
    if (N == 1):
        return 1
    if (N < 3):
        return 0
    if (N == 3):
        cnt = 0
        if abs(arr[0] - arr[1]) == K:
            cnt += 1
        if abs(arr[2] - arr[1]) == K:
            cnt += 1
        if abs(arr[0] - arr[2]) == K:
            cnt += 1
        return cnt
    prefix = [0] * (N + 2)
    suffix = [0] * (N + 2)
    prefix[0] = arr[0]
    prefix[1] = arr[1]
    suffix[N - 1] = arr[N - 1]
    suffix[N - 2] = arr[N - 2]
    for i in range(2, N, 2):
        prefix[i] = arr[i] + prefix[i - 2]
    for i in range(3, N, 2):
        prefix[i] = arr[i] + prefix[i - 2]
    for i in range(N - 3, -1, -2):
        suffix[i] = arr[i] + suffix[i + 2]
    for i in range(N - 4, -1, -2):
        suffix[i] = arr[i] + suffix[i + 2]
    count = 0
    for i in range(2, N):
        if (abs(prefix[i - 1] + suffix[i + 2] -
                prefix[i - 2] - suffix[i + 1]) == K):
            count += 1
    count += findCount0th(arr, N, K)
    count += findCount1st(arr, N, K)
    return count


if __name__ == "__main__":
    arr = [1, 2, 4, 5, 6]
    K = 2
    print(countTimes(arr, K))

# Expected output:
2
# replace ' ? ' in a string such that no two adjacent characters are same | function that replace all ' ? ' with lowercase alphabets such that each adjacent character is different ; store the given string ; if the first character is '? ; traverse the string [ 1 , n - 1 ] ; if the current character is '? ; change the character ; check equality with the previous character ; check equality with the next character ; check equality with the previous character ; if the last character is '? ; change character ; check with previous character ; return the resultant string ; 
def changeString(S):

    N = len(S)
    s = [' '] * (len(S))

    for i in range(len(S)):
        s[i] = S[i]

    if (s[0] == '?'):
        s[0] = 'a'

        if (s[0] == s[1]):
            s[0] = chr(ord(s[0]) + 1)

    for i in range(1, N - 1):

        if (s[i] == '?'):

            s[i] = 'a'

            if (s[i] == s[i - 1]):
                s[i] = chr(ord(s[i]) + 1)

            if (s[i] == s[i + 1]):
                s[i] = chr(ord(s[i]) + 1)

            if (s[i] == s[i - 1]):
                s[i] = chr(ord(s[i]) + 1)

    if (s[N - 1] == '?'):

        s[N - 1] = 'a'

        if (s[N - 1] == s[N - 2]):
            s[N - 1] += 1

    ans = ""
    for i in range(len(s)):
        ans += s[i]

    return ans


if __name__ == '__main__':
    S = "?a?a"

    print(changeString(S))

# Expected output:
baba
# check if a given string is a reverse bitonic string or not | function to check if the given string is reverse bitonic ; check for decreasing sequence ; if end of string has been reached ; check for increasing sequence ; if the end of string hasn 't  been reached ; if reverse bitonic ; 
def checkReverseBitonic(s):
    i = 0
    j = 0
    for i in range(len(s)):
        if (s[i] < s[i - 1]):
            continue
        if (s[i] >= s[i - 1]):
            break
    if (i == len(s) - 1):
        return 1
    for j in range(i + 1, len(s)):
        if (s[j] > s[j - 1]):
            continue
        if (s[j] <= s[j - 1]):
            break
    i = j
    if (i != len(s)):
        return 0
    return 1


s = "abcdwef"
if (checkReverseBitonic(s) == 1):
    print("YES")
else:
    print("NO")

# Expected output:
NO
# smallest number whose square has n digits | python3 program to find the smallest number whose square has n digits ; function to return smallest number whose square has n digits ; calculate n - th term of the series ; 

import math


def smallestNum(N):
    x = pow(10.0, (N - 1) / 2.0)
    return math .ceil(x)


N = 4
print(smallestNum(N))

# Expected output:
32
# count of k | function to to count the number of k - countdowns for multiple queries ; flag which stores the current value of value in the countdown ; count of k - countdowns ; loop to iterate over the elements of the array ; condition check if the elements of the array is equal to k ; condition check if the elements of the array is in continuous order ; condition check if the elements of the array are not in continuous order ; condition check to increment the counter if the there is a k - countdown present in the array ; returning the count of k - countdowns ; 
def countKCountdown(arr, N, K):
    flag = -1
    count = 0
    for i in range(0, N):
        if (arr[i] == K):
            flag = K
        if (arr[i] == flag):
            flag -= 1
        else:
            flag = -1
        if (flag == 0):
            count += 1
    return count


N = 8
K = 3
arr = [4, 3, 2, 1, 5, 3, 2, 1]
print(countKCountdown(arr, N, K))

# Expected output:
2
# convert the given rgb color code to hex color code | function to convert decimal to hexadecimal ; char array to store hexadecimal number ; counter for hexadecimal number array ; temporary variable to store remainder ; storing remainder in temp variable . ; check if temp < 10 ; return the equivalent hexadecimal color code ; function to convert the rgb code to hex color code ; the hex color code doesn 't exist ; 
def decToHexa(n):
    hexaDeciNum = ['0'] * 100
    i = 0
    while (n != 0):
        temp = 0
        temp = n % 16
        if (temp < 10):
            hexaDeciNum[i] = chr(temp + 48)
            i = i + 1
        else:
            hexaDeciNum[i] = chr(temp + 55)
            i = i + 1
        n = int(n / 16)
    hexCode = ""
    if (i == 2):
        hexCode = hexCode + hexaDeciNum[0]
        hexCode = hexCode + hexaDeciNum[1]
    elif (i == 1):
        hexCode = "0"
        hexCode = hexCode + hexaDeciNum[0]
    elif (i == 0):
        hexCode = "00"
    return hexCode


def convertRGBtoHex(R, G, B):
    if ((R >= 0 and R <= 255) and (G >= 0 and G <= 255) and (B >= 0 and B <= 255)):
        hexCode = "#"
        hexCode = hexCode + decToHexa(R)
        hexCode = hexCode + decToHexa(G)
        hexCode = hexCode + decToHexa(B)
        return hexCode
    else:
        return "-1"


R = 0
G = 0
B = 0
print(convertRGBtoHex(R, G, B))
R = 255
G = 255
B = 255
print(convertRGBtoHex(R, G, B))
R = 25
G = 56
B = 123
print(convertRGBtoHex(R, G, B))
R = 2
G = 3
B = 4
print(convertRGBtoHex(R, G, B))
R = 255
G = 255
B = 256
print(convertRGBtoHex(R, G, B))

# Expected output:
#000000
#FFFFFF
#9183B7
#020304
-1
# strings formed from given characters without any consecutive repeating characters | function to print the strings which satisfy the mentioned conditions ; iterate through all the strings in the array . ; check function to check the conditions for every string ; function to check whether the string contains any consecutive repetitive characters and any characters other than those in str ; valid characters check ; nonrepetitive check ; 
def check(s, strr):
    chars = s
    for c in chars:
        if c not in strr:
            return False
    for i in range(len(chars) - 1):
        if (chars[i] == chars[i + 1]):
            return False
    return True

def getStrings(strr, arr):
    for i in range(len(arr)):
        if (check(arr[i], strr)):
            print(arr[i], end=" ")


strr = "ABCD"
arr = ["AABCDA", "ABCDZADC", "ABCDBCA", "ABCDABDCA"]
getStrings(strr, arr)

# Expected output:
ABCDBCA ABCDABDCA