giulio98/xlcost-single-prompt huggingface dataset:
# count of subsets not containing adjacent elements | function to return the count of possible subsets ; total possible subsets of n sized array is ( 2 ^ n - 1 ) ; to store the required count of subsets ; run from i 000. .0 to 111. .1 ; if current subset has consecutive elements from the array ; 
def cntSubsets(arr, n):
    max = pow(2, n)
    result = 0
    for i in range(max):
        counter = i
        if (counter & (counter >> 1)):
            continue
        result += 1
    return result


arr = [3, 5, 7]
n = len(arr)
print(cntSubsets(arr, n))

# Expected output:
5
# count of subsets not containing adjacent elements | function to return the count of possible subsets ; if previous element was 0 then 0 as well as 1 can be appended ; if previous element was 1 then only 0 can be appended ; store the count of all possible subsets ; 
def cntSubsets(arr, n):
    a = [0] * n
    b = [0] * n
    a[0] = b[0] = 1
    for i in range(1, n):
        a[i] = a[i - 1] + b[i - 1]
        b[i] = a[i - 1]
    result = a[n - 1] + b[n - 1]
    return result


if __name__ == "__main__":
    arr = [3, 5, 7]
    n = len(arr)
    print(cntSubsets(arr, n))

# Expected output:
5
# maximum perimeter of a square in a 2d grid | function to calculate the perfix sum of the rows and the columns of the given matrix ; number of rows and cols ; first column of the row prefix array ; update the prefix sum for the rows ; first row of the column prefix array ; update the prefix sum for the columns ; function to return the perimeter of the square having top - left corner at ( i , j ) and size k ; i and j represent the top left corner of the square and k is the size ; get the upper row sum ; get the left column sum ; at the distance of k in both direction ; the perimeter will be sum of all the values ; since all the corners are included twice , they need to be subtract from the sum ; function to return the maximum perimeter of a square in the given matrix ; number of rows and cols ; function call to calculate the prefix sum of rows and cols ; to store the maximum perimeter ; nested loops to choose the top - left corner of the square ; loop for the size of the square ; get the perimeter of the current square ; update the maximum perimeter so far ; 
def perfix_calculate(A, row, col):
    n = len(A)
    m = len(A[0])
    for i in range(n):
        row[i][0] = A[i][0]
    for i in range(n):
        for j in range(1, m):
            row[i][j] = row[i][j - 1] + A[i][j]
    for i in range(m):
        col[0][i] = A[0][i]
    for i in range(m):
        for j in range(1, m):
            col[j][i] = A[j][i] + col[j - 1][i]


def perimeter(i, j, k, row, col, A):
    row_s, col_s = 0, 0
    if (j == 0):
        row_s = 0
    else:
        row_s = row[i][j - 1]
    if (i == 0):
        col_s = 0
    else:
        col_s = col[i - 1][j]
    upper_row = row[i][j + k] - row_s
    left_col = col[i + k][j] - col_s
    if (j == 0):
        row_s = 0
    else:
        row_s = row[i + k][j - 1]
    if (i == 0):
        col_s = 0
    else:
        col_s = col[i - 1][j + k]
    lower_row = row[i + k][j + k] - row_s
    right_col = col[i + k][j + k] - col_s
    sum = upper_row + lower_row + left_col + right_col
    sum -= (A[i][j] + A[i + k][j] + A[i][j + k] + A[i + k][j + k])
    return sum


def maxPerimeter(A):
    n = len(A)
    m = len(A[0])
    row = [[0 for i in range(m)]for i in range(n)]
    col = [[0 for i in range(m)]for i in range(n)]
    perfix_calculate(A, row, col)
    maxPer = 0
    for i in range(n):
        for j in range(m):
            for k in range(min(n - i, m - j)):
                perimtr = perimeter(i, j, k, row, col, A)
                maxPer = max(maxPer, perimtr)
    return maxPer


A = [[1, 1, 0], [1, 1, 1], [0, 1, 1]]
print(maxPerimeter(A))

# Expected output:
6
# optimal strategy for a game | set 3 | calculates the maximum score possible for p1 if only the bags from beg to ed were available ; length of the game ; which turn is being played ; base case i . e last turn ; if it is p1 's turn ; if p2 's turn ; player picks money from the left end ; player picks money from the right end ; if it is player 1 's turn then  current picked score added to  his total. choose maximum of  the two scores as p1 tries to  maximize his score. ; if player 2 ' s ▁ turn ▁ don ' t add current picked bag score to total . choose minimum of the two scores as p2 tries to minimize p1 's score. ; 
def maxScore(money, beg, ed):
    totalTurns = len(money)
    turnsTillNow = beg + ((totalTurns - 1) - ed)
    if (beg == ed):
        if (turnsTillNow % 2 == 0):
            return [money[beg], "L"]
        else:
            return [0, "L"]
    scoreOne = maxScore(money, beg + 1, ed)
    scoreTwo = maxScore(money, beg, ed - 1)
    if (turnsTillNow % 2 == 0):
        if (money[beg] + scoreOne[0] > money[ed] + scoreTwo[0]):
            return [money[beg] + scoreOne[0], "L" + scoreOne[1]]
        else:
            return [money[ed] + scoreTwo[0], "R" + scoreTwo[1]]
    else:
        if (scoreOne[0] < scoreTwo[0]):
            return [scoreOne[0], "L" + scoreOne[1]]
        else:
            return [scoreTwo[0], "R" + scoreTwo[1]]


ar = [10, 80, 90, 30]
arraySize = len(ar)
bags = ar
ans = maxScore(bags, 0, arraySize - 1)
print(ans[0], ans[1])

# Expected output:
110 RRRL
# minimum number of fibonacci jumps to reach end | a dynamic programming based python3 program to find minimum number of jumps to reach destination ; function that returns the min number of jump to reach the destination ; we consider only those fibonacci numbers which are less than n , where we can consider fib [ 30 ] to be the upper bound as this will cross 10 ^ 5 ; dp [ i ] will be storing the minimum number of jumps required for the position i . so dp [ n + 1 ] will have the result we consider 0 as source and n + 1 as the destination ; base case ( steps to reach source is ) ; initialize all table values as infinite ; go through each positions till destination . ; calculate the minimum of that position if all the fibonacci numbers are considered ; if the position is safe or the position is the destination then only we calculate the minimum otherwise the cost is max as default ; - 1 denotes if there is no path possible ; 

MAX = 1e9


def minJumps(arr, N):
    fib = [0 for i in range(30)]
    fib[0] = 0
    fib[1] = 1
    for i in range(2, 30):
        fib[i] = fib[i - 1] + fib[i - 2]
    DP = [0 for i in range(N + 2)]
    DP[0] = 0
    for i in range(1, N + 2):
        DP[i] = MAX
    for i in range(1, N + 2):
        for j in range(1, 30):
            if ((arr[i - 1] == 1 or i == N + 1) and i - fib[j] >= 0):
                DP[i] = min(DP[i], 1 + DP[i - fib[j]])
    if (DP[N + 1] != MAX):
        return DP[N + 1]
    else:
        return -1


arr = [0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0]
n = len(arr)
print(minJumps(arr, n - 1))

# Expected output:
3
# subsequence x of length k such that gcd ( x [ 0 ] , x [ 1 ] ) + ( x [ 2 ] , x [ 3 ] ) + ... is maximized | python3 program to find the sum of the addition of all possible subsets ; recursive function to find the maximum value of the given recurrence ; if we get k elements ; if we have reached the end and k elements are not there ; if the state has been visited ; iterate for every element as the next possible element and take the element which gives the maximum answer ; if this element is the first element in the individual pair in the subsequence then simply recurrence with the last element as i - th index ; if this element is the second element in the individual pair , the find gcd with the previous element and add to the answer and recur for the next element ; 

from math import gcd as __gcd
MAX = 100


def recur(ind, cnt, last, a, n, k, dp):
    if (cnt == k):
        return 0
    if (ind == n):
        return -10 ** 9
    if (dp[ind][cnt] != -1):
        return dp[ind][cnt]
    ans = 0
    for i in range(ind, n):
        if (cnt % 2 == 0):
            ans = max(ans, recur(i + 1, cnt + 1, i, a, n, k, dp))
        else:
            ans = max(
                ans,
                __gcd(
                    a[last],
                    a[i]) +
                recur(
                    i +
                    1,
                    cnt +
                    1,
                    0,
                    a,
                    n,
                    k,
                    dp))
    dp[ind][cnt] = ans
    return ans


a = [4, 5, 3, 7, 8, 10, 9, 8]
n = len(a)
k = 4
dp = [[-1 for i in range(MAX)]for i in range(n)]
print(recur(0, 0, 0, a, n, k, dp))

# Expected output:
9
# maximum number of given operations to remove the entire string | function to return the maximum number of given operations required to remove the given entirely ; if length of the is zero ; single operation can delete the entire string ; to store the prefix of the string which is to be deleted ; prefix s [ 0. . i ] ; to store the subs [ i + 1. . .2 * i + 1 ] ; if the prefix s [ 0. . . i ] can be deleted ; 1 operation to remove the current prefix and then recursively find the count of operations for the subs [ i + 1. . . n - 1 ] ; entire has to be deleted ; 
def find(s):
    if (len(s) == 0):
        return 0
    c = 1
    d = ""
    for i in range(len(s)):
        d += s[i]
        s2 = s[i + 1:i + 1 + len(d)]
        if (s2 == d):
            c = 1 + find(s[i + 1:])
            break
    return c


s = "abababab"
print(find(s))

# Expected output:
4
# divide the array in k segments such that the sum of minimums is maximized | python 3 program to find the sum of the minimum of all the segments ; function to maximize the sum of the minimums ; if k segments have been divided ; if we are at the end ; if we donot reach the end then return a negative number that cannot be the sum ; if at the end but k segments are not formed ; if the state has been visited already ; if the state has not been visited ; get the minimum element in the segment ; iterate and try to break at every index and create a segment ; find the minimum element in the segment ; find the sum of all the segments trying all the possible combinations ; return the answer by memoizing it ; 

MAX = 10


def maximizeSum(a, n, ind, k, dp):
    if (k == 0):
        if (ind == n):
            return 0
        else:
            return -1e9
    elif (ind == n):
        return -1e9
    elif (dp[ind][k] != -1):
        return dp[ind][k]
    else:
        ans = 0
        mini = a[ind]
        for i in range(ind, n, 1):
            mini = min(mini, a[i])
            ans = max(ans, maximizeSum(a, n, i + 1, k - 1, dp) + mini)
        dp[ind][k] = ans
        return ans


if __name__ == '__main__':
    a = [5, 7, 4, 2, 1, 6]
    k = 3
    n = len(a)
    dp = [[-1 for i in range(MAX)] for j in range(MAX)]
    print(maximizeSum(a, n, 0, k, dp))

# Expected output:
13
# optimally accommodate 0 s and 1 s from a binary string into k buckets | function to find the minimum required sum using dynamic programming ; if both start and bucket reached end then return 0 else that arrangement is not possible so return int_max ; corner case ; if state if already calculated then return its answer ; start filling zeroes and ones which to be accommodated in jth bucket then ans for current arrangement will be ones * zeroes + recur ( i + 1 , bucket + 1 ) ; if this arrangement is not possible then don 't calculate further ; function to initialize the dp and call solveutil ( ) method to get the answer ; start with 0 - th index and 1 bucket ; 
def solveUtil(start, bucket, str1, K, dp):
    N = len(str1)
    if (start == N):
        if (bucket == K):
            return 0
        return 10 ** 9
    if (bucket == K):
        return 10 ** 9
    if (dp[start][bucket] != -1):
        return dp[start][bucket]
    zeroes = 0
    ones = 0
    ans = 10 ** 9
    for i in range(start, N):
        if (str1[i] == '1'):
            ones += 1
        else:
            zeroes += 1
        if (ones * zeroes > ans):
            break
        temp = solveUtil(i + 1, bucket + 1, str1, K, dp)
        if (temp != 10 ** 9):
            ans = min(ans, temp + (ones * zeroes))
    dp[start][bucket] = ans
    return ans


def solve(str1, K):
    N = len(str1)
    dp = [[-1 for i in range(K)]for i in range(N)]
    ans = solveUtil(0, 0, str1, K, dp)
    if ans == 10 ** 9:
        return -1
    else:
        return ans


s = "0101"
S = [i for i in s]
K = 2
print(solve(S, K))

# Expected output:
2
# probability of getting more heads than tails when n biased coins are tossed | python3 implementation of the above approach ; function to return the probability when number of heads is greater than the number of tails ; declaring the dp table ; base case ; iterating for every coin ; j represents the numbers of heads ; if number of heads is equal to zero there there is only one possibility ; when the number of heads is greater than ( n + 1 ) / 2 it means that heads are greater than tails as no of tails + no of heads is equal to n for any permutation of heads and tails ; 

import numpy as np


def Probability(p, n):
    dp = np .zeros((n + 1, n + 1))
    for i in range(n + 1):
        for j in range(n + 1):
            dp[i][j] = 0.0
    dp[0][0] = 1.0
    for i in range(1, n + 1):
        for j in range(i + 1):
            if (j == 0):
                dp[i][j] = dp[i - 1][j] * (1.0 - p[i])
            else:
                dp[i][j] = (dp[i - 1][j] * (1.0 - p[i]) +
                            dp[i - 1][j - 1] * p[i])
    ans = 0.0
    for i in range((n + 1) // 2, n + 1):
        ans += dp[n][i]
    return ans


if __name__ == "__main__":
    p = [0.0, 0.3, 0.4, 0.7]
    n = len(p) - 1
    print(Probability(p, n))

# Expected output:
0.44199999999999995
# number of ways to get a given sum with n number of m | python3 function to calculate the number of ways to achieve sum x in n no of throws ; function to calculate recursively the number of ways to get sum in given throws and [ 1. . m ] values ; base condition 1 ; base condition 2 ; if value already calculated dont move into re - computation ; recursively moving for sum - i in throws - 1 no of throws left ; inserting present values in dp ; 

import numpy as np
mod = 1000000007
dp = np .zeros((55, 55))


def NoofWays(face, throws, sum):
    if (sum == 0 and throws == 0):
        return 1
    if (sum < 0 or throws == 0):
        return 0
    if (dp[throws][sum] != -1):
        return dp[throws][sum]
    ans = 0
    for i in range(1, face + 1):
        ans += NoofWays(face, throws - 1, sum - i)
    dp[throws][sum] = ans
    return ans


if __name__ == "__main__":
    faces = 6
    throws = 3
    sum = 12
    for i in range(55):
        for j in range(55):
            dp[i][j] = -1
    print(NoofWays(faces, throws, sum))

# Expected output:
25.0
# longest sub | function to return the length of the longest required sub - sequence ; sort the array ; to store the resultant length ; if array contains only one element then it divides itself ; every element divides itself ; count for all numbers which are lesser than a [ i ] ; if a [ i ] % a [ j ] then update the maximum subsequence length , dp [ i ] = max ( dp [ i ] , 1 + dp [ j ] ) where j is in the range [ 0 , i - 1 ] ; if array contains only one element then i = j which doesn 't satisfy the condition ; 
def find(n, a):
    a .sort()
    res = 1
    dp = [0] * n
    dp[0] = 1
    for i in range(1, n):
        dp[i] = 1
        for j in range(i):
            if (a[i] % a[j] == 0):
                dp[i] = max(dp[i], 1 + dp[j])
        res = max(res, dp[i])
    if (res == 1):
        return -1
    else:
        return res


if __name__ == "__main__":
    a = [2, 4, 6, 1, 3, 11]
    n = len(a)
    print(find(n, a))

# Expected output:
3
# maximize the happiness of the groups on the trip | python3 implementation of the approach ; function to return the maximized happiness ; two arrays similar to 0 1 knapsack problem ; to store the happiness of the current group ; current person is a child ; woman ; man ; old person ; group 's happiness is the sum of happiness  of the people in the group multiplied by  the number of people ; solution using 0 1 knapsack ; 

import numpy as np


def MaxHappiness(A, N, v):
    val = [0] * N
    wt = [0] * N
    c = 0
    for i in range(N):
        string = v[i]
        c = 0
        for j in range(len(string)):
            if (string[j] == 'c'):
                c += 4
            elif (string[j] == 'w'):
                c += 3
            elif (string[j] == 'm'):
                c += 2
            else:
                c += 1
        c *= len(string)
        val[i] = c
        wt[i] = len(string)
    k = np .zeros((N + 1, A + 1))
    for i in range(N + 1):
        for w in range(A + 1):
            if (i == 0 or w == 0):
                k[i][w] = 0
            elif (wt[i - 1] <= w):
                k[i][w] = max(val[i - 1] + k[i - 1]
                              [w - wt[i - 1]], k[i - 1][w])
            else:
                k[i][w] = k[i - 1][w]
    return k[N][A]


if __name__ == "__main__":
    A = 5
    v = ["mmo", "oo", "cmw", "cc", "c"]
    N = len(v)
    print(MaxHappiness(A, N, v))

# Expected output:
43.0
# find maximum path sum in a 2d matrix when exactly two left moves are allowed | python3 program to find maximum path sum in a 2d matrix when exactly two left moves are allowed ; function to return the maximum path sum ; copy last column i . e . starting and ending columns in another array ; calculate suffix sum in each row ; select the path we are going to follow ; 

import numpy as np
N = 3
M = 3


def findMaxSum(arr):
    sum = 0
    b = np .zeros((N, M))
    for i in range(N):
        b[i][M - 1] = arr[i][M - 1]
    for i in range(N):
        for j in range(M - 2, -1, -1):
            b[i][j] = arr[i][j] + b[i][j + 1]
    for i in range(1, N):
        for j in range(M):
            sum = max(sum, b[i][j] + b[i - 1][j])
            b[i][j] = max(b[i][j], b[i - 1][j] + arr[i][j])
    return sum


if __name__ == "__main__":
    arr = [[3, 7, 4], [1, 9, 6], [1, 7, 7]]
    print(findMaxSum(arr))

# Expected output:
34.0
# maximum sum in an array such that every element has exactly one adjacent element to it | python 3 implementation of the approach ; to store the states of dp ; function to return the maximized sum ; base case ; checks if a state is already solved ; recurrence relation ; return the result ; 

arrSize = 51
dp = [0 for i in range(arrSize)]
v = [False for i in range(arrSize)]


def sumMax(i, arr, n):
    if (i >= n - 1):
        return 0
    if (v[i]):
        return dp[i]
    v[i] = True
    dp[i] = max(arr[i] + arr[i + 1] + sumMax(i +
                3, arr, n), sumMax(i + 1, arr, n))
    return dp[i]


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

# Expected output:
2
# maximum sum subsequence of length k | python program to calculate the maximum sum of increasing subsequence of length k ; in the implementation dp [ n ] [ k ] represents maximum sum subsequence of length k and the subsequence is ending at index n . ; initializing whole multidimensional dp array with value - 1 ; for each ith position increasing subsequence of length 1 is equal to that array ith value so initializing dp [ i ] [ 1 ] with that array value ; starting from 1 st index as we have calculated for 0 th index . computing optimized dp values in bottom - up manner ; check for increasing subsequence ; proceed if value is pre calculated ; check for all the subsequences ending at any j < i and try including element at index i in them for some length l . update the maximum value for every length . ; the final result would be the maximum value of dp [ i ] [ k ] for all different i . ; when no subsequence of length k is possible sum would be considered zero ; 
def MaxIncreasingSub(arr, n, k):
    dp = [-1] * n
    ans = -1
    for i in range(n):
        dp[i] = [-1] * (k + 1)
    for i in range(n):
        dp[i][1] = arr[i]
    for i in range(1, n):
        for j in range(i):
            if arr[j] < arr[i]:
                for l in range(1, k):
                    if dp[j][l] != -1:
                        dp[i][l + 1] = max(dp[i][l + 1], dp[j][l] + arr[i])
    for i in range(n):
        if ans < dp[i][k]:
            ans = dp[i][k]
    return (0 if ans == -1 else ans)


if __name__ == "__main__":
    n, k = 8, 3
    arr = [8, 5, 9, 10, 5, 6, 21, 8]
    ans = MaxIncreasingSub(arr, n, k)
    print(ans)

# Expected output:
40
# generate all unique partitions of an integer | set 2 | array to store the numbers used to form the required sum ; function to print the array which contains the unique partitions which are used to form the required sum ; function to find all the unique partitions remsum = remaining sum to form maxval is the maximum number that can be used to make the partition ; if remsum == 0 that means the sum is achieved so print the array ; i will begin from maxval which is the maximum value which can be used to form the sum ; store the number used in forming sum gradually in the array ; since i used the rest of partition cant have any number greater than i hence second parameter is i ; 

dp = [0 for i in range(200)]
count = 0


def print1(idx):
    for i in range(1, idx, 1):
        print(dp[i], end=" ")
    print("", end="")


def solve(remSum, maxVal, idx, count):
    if (remSum == 0):
        print1(idx)
        count += 1
        return
    i = maxVal
    while (i >= 1):
        if (i > remSum):
            i -= 1
            continue
        elif (i <= remSum):
            dp[idx] = i
            solve(remSum - i, i, idx + 1, count)
            i -= 1


if __name__ == '__main__':
    n = 4
    count = 0
    solve(n, n, 1, count)

# Expected output:
4 3 1 2 2 2 1 1 1 1 1 1
# maximum sum such that no two elements are adjacent | set 2 | python 3 program to implement above approach ; variable to store states of dp ; variable to check if a given state has been solved ; function to find the maximum sum subsequence such that no two elements are adjacent ; base case ; to check if a state has been solved ; required recurrence relation ; returning the value ; 

maxLen = 10
dp = [0 for i in range(maxLen)]
v = [0 for i in range(maxLen)]


def maxSum(arr, i, n):
    if (i >= n):
        return 0
    if (v[i]):
        return dp[i]
    v[i] = 1
    dp[i] = max(maxSum(arr, i + 1, n), arr[i] + maxSum(arr, i + 2, n))
    return dp[i]


if __name__ == '__main__':
    arr = [12, 9, 7, 33]
    n = len(arr)
    print(maxSum(arr, 0, n))

# Expected output:
45
# optimal strategy for a game | set 2 | python3 program to find out maximum value from a given sequence of coins ; for both of your choices , the opponent gives you total sum minus maximum of his value ; returns optimal value possible that a player can collect from an array of coins of size n . note than n must be even ; compute sum of elements ; initialize memoization table ; 

MAX = 100
memo = [[0 for i in range(MAX)]for j in range(MAX)]


def oSRec(arr, i, j, Sum):
    if (j == i + 1):
        return max(arr[i], arr[j])
    if (memo[i][j] != -1):
        return memo[i][j]
    memo[i][j] = max((Sum - oSRec(arr, i + 1, j, Sum - arr[i])),
                     (Sum - oSRec(arr, i, j - 1, Sum - arr[j])))
    return memo[i][j]


def optimalStrategyOfGame(arr, n):
    Sum = 0
    Sum = sum(arr)
    for j in range(MAX):
        for k in range(MAX):
            memo[j][k] = -1
    return oSRec(arr, 0, n - 1, Sum)


arr1 = [8, 15, 3, 7]
n = len(arr1)
print(optimalStrategyOfGame(arr1, n))
arr2 = [2, 2, 2, 2]
n = len(arr2)
print(optimalStrategyOfGame(arr2, n))
arr3 = [20, 30, 2, 2, 2, 10]
n = len(arr3)
print(optimalStrategyOfGame(arr3, n))

# Expected output:
22
4
42