giulio98/xlcost-single-prompt huggingface dataset:
# minimum sum of product of two arrays | function to find the minimum product ; find product of current elements and update result . ; if both product and b [ i ] are negative , we must increase value of a [ i ] to minimize result . ; if both product and a [ i ] are negative , we must decrease value of a [ i ] to minimize result . ; similar to above two cases for positive product . ; check if current difference becomes higher than the maximum difference so far . ; 
def minproduct(a, b, n, k):
    diff = 0
    res = 0
    for i in range(n):
        pro = a[i] * b[i]
        res = res + pro
        if (pro < 0 and b[i] < 0):
            temp = (a[i] + 2 * k) * b[i]
        elif (pro < 0 and a[i] < 0):
            temp = (a[i] - 2 * k) * b[i]
        elif (pro > 0 and a[i] < 0):
            temp = (a[i] + 2 * k) * b[i]
        elif (pro > 0 and a[i] > 0):
            temp = (a[i] - 2 * k) * b[i]
        d = abs(pro - temp)
        if (d > diff):
            diff = d
    return res - diff


a = [2, 3, 4, 5, 4]
b = [3, 4, 2, 3, 2]
n = 5
k = 3
print(minproduct(a, b, n, k))

# Expected output:
25
# split n into maximum composite numbers | function to calculate the maximum number of composite numbers adding upto n ; 4 is the smallest composite number ; stores the remainder when n is divided n is divided by 4 ; if remainder is 0 , then it is perfectly divisible by 4. ; if the remainder is 1 ; if the number is less then 9 , that is 5 , then it cannot be expressed as 4 is the only composite number less than 5 ; if the number is greater then 8 , and has a remainder of 1 , then express n as n - 9 a and it is perfectly divisible by 4 and for 9 , count 1. ; when remainder is 2 , just subtract 6 from n , so that n is perfectly divisible by 4 and count 1 for 6 which is subtracted . ; if the number is 7 , 11 which cannot be expressed as sum of any composite numbers ; when the remainder is 3 , then subtract 15 from it and n becomes perfectly divisible by 4 and we add 2 for 9 and 6 , which is getting subtracted to make n perfectly divisible by 4. ; 
def count(n):
    if (n < 4):
        return -1
    rem = n % 4
    if (rem == 0):
        return n // 4
    if (rem == 1):
        if (n < 9):
            return -1
        return (n - 9) // 4 + 1
    if (rem == 2):
        return (n - 6) // 4 + 1
    if (rem == 3):
        if (n < 15):
            return -1
        return (n - 15) // 4 + 2


n = 90
print(count(n))
n = 143
print(count(n))

# Expected output:
22
34
# policemen catch thieves | returns maximum number of thieves that can be caught . ; store indices in list ; track lowest current indices of thief : thi [ l ] , police : pol [ r ] ; can be caught ; increment the minimum index ; 
def policeThief(arr, n, k):
    i = 0
    l = 0
    r = 0
    res = 0
    thi = []
    pol = []
    while i < n:
        if arr[i] == 'P':
            pol .append(i)
        elif arr[i] == 'T':
            thi .append(i)
        i += 1
    while l < len(thi) and r < len(pol):
        if (abs(thi[l] - pol[r]) <= k):
            res += 1
            l += 1
            r += 1
        elif thi[l] < pol[r]:
            l += 1
        else:
            r += 1
    return res


if __name__ == '__main__':
    arr1 = ['P', 'T', 'T', 'P', 'T']
    k = 2
    n = len(arr1)
    print(("Maximum thieves caught: {}".format(policeThief(arr1, n, k))))
    arr2 = ['T', 'T', 'P', 'P', 'T', 'P']
    k = 2
    n = len(arr2)
    print(("Maximum thieves caught: {}".format(policeThief(arr2, n, k))))
    arr3 = ['P', 'T', 'P', 'T', 'T', 'P']
    k = 3
    n = len(arr3)
    print(("Maximum thieves caught: {}".format(policeThief(arr3, n, k))))

# Expected output:
Maximum thieves caught: 2
Maximum thieves caught: 3
Maximum thieves caught: 3
# minimum rotations to unlock a circular lock | function for min rotation ; iterate till input and unlock code become 0 ; input and unlock last digit as reminder ; find min rotation ; update code and input ; 
def minRotation(input, unlock_code):
    rotation = 0
    while (input > 0 or unlock_code > 0):
        input_digit = input % 10
        code_digit = unlock_code % 10
        rotation += min(abs(input_digit - code_digit),
                        10 - abs(input_digit - code_digit))
        input = int(input / 10)
        unlock_code = int(unlock_code / 10)
    return rotation


input = 28756
unlock_code = 98234
print("Minimum Rotation =", minRotation(input, unlock_code))

# Expected output:
Minimum Rotation = 12
# job scheduling with two jobs allowed at a time | python3 program to check if all jobs can be scheduled if two jobs are allowed at a time . ; making a pair of starting and ending time of job ; sorting according to starting time of job ; starting first and second job simultaneously ; checking if starting time of next new job is greater than ending time of currently scheduled first job ; checking if starting time of next new job is greater than ending time of ocurrently scheduled second job ; 
def checkJobs(startin, endin, n):
    a = []
    for i in range(0, n):
        a .append([startin[i], endin[i]])
    a .sort()
    tv1 = a[0][1]
    tv2 = a[1][1]
    for i in range(2, n):
        if (a[i][0] >= tv1):
            tv1 = tv2
            tv2 = a[i][1]
        elif (a[i][0] >= tv2):
            tv2 = a[i][1]
        else:
            return 0
    return 1


if __name__ == '__main__':
    startin = [1, 2, 4]
    endin = [2, 3, 5]
    n = 3
    print(checkJobs(startin, endin, n))

# Expected output:
1
# program for worst fit algorithm in memory management | function to allocate memory to blocks as per worst fit algorithm ; initially no block is assigned to any process ; pick each process and find suitable blocks according to its size ad assign to it ; find the best fit block for current process ; if we could find a block for current process ; allocate block j to p [ i ] process ; reduce available memory in this block . ; 
def worstFit(blockSize, m, processSize, n):
    allocation = [-1] * n
    for i in range(n):
        wstIdx = -1
        for j in range(m):
            if blockSize[j] >= processSize[i]:
                if wstIdx == -1:
                    wstIdx = j
                elif blockSize[wstIdx] < blockSize[j]:
                    wstIdx = j
        if wstIdx != -1:
            allocation[i] = wstIdx
            blockSize[wstIdx] -= processSize[i]
    print("Process No. Process Size Block no.")
    for i in range(n):
        print(i + 1, " ", processSize[i], end=" ")
        if allocation[i] != -1:
            print(allocation[i] + 1)
        else:
            print("Not Allocated")


if __name__ == '__main__':
    blockSize = [100, 500, 200, 300, 600]
    processSize = [212, 417, 112, 426]
    m = len(blockSize)
    n = len(processSize)
    worstFit(blockSize, m, processSize, n)

# Expected output:
Process No. Process Size Block no.
1   212 5
2   417 2
3   112 5
4   426 Not Allocated
# maximize array sum after k negations | set 1 | this function does k operations on array in a way that maximize the array sum . index -- > stores the index of current minimum element for j 'th operation ; modify array k number of times ; find minimum element in array for current operation and modify it i . e ; arr [ j ] -- > - arr [ j ] ; this the condition if we find 0 as minimum element , so it will useless to replace 0 by - ( 0 ) for remaining operations ; modify element of array ; calculate sum of array ; 
def maximumSum(arr, n, k):
    for i in range(1, k + 1):
        min = +2147483647
        index = -1
        for j in range(n):
            if (arr[j] < min):
                min = arr[j]
                index = j
        if (min == 0):
            break
        arr[index] = -arr[index]
    sum = 0
    for i in range(n):
        sum += arr[i]
    return sum


arr = [-2, 0, 5, -1, 2]
k = 4
n = len(arr)
print(maximumSum(arr, n, k))

# Expected output:
10
# maximize array sum after k negations | set 1 | python3 program to find maximum array sum after at most k negations ; sorting given array using in - built java sort function ; if we find a 0 in our sorted array , we stop ; calculating sum ; 
def sol(arr, k):
    arr .sort()
    Sum = 0
    i = 0
    while (k > 0):
        if (arr[i] >= 0):
            k = 0
        else:
            arr[i] = (-1) * arr[i]
            k = k - 1
        i += 1
    for j in range(len(arr)):
        Sum += arr[j]
    return Sum


arr = [-2, 0, 5, -1, 2]
print(sol(arr, 4))

# Expected output:
10
# maximize array sum after k negations | set 1 | function to calculate sum of the array ; iterate from 0 to n - 1 ; function to maximize sum ; iterate from 0 to n - 1 ; 
def sumArray(arr, n):
    sum = 0
    for i in range(n):
        sum += arr[i]
    return sum


def maximizeSum(arr, n, k):
    arr .sort()
    i = 0
    for i in range(n):
        if (k and arr[i] < 0):
            arr[i] *= -1
            k -= 1
            continue
        break
    if (i == n):
        i -= 1
    if (k == 0 or k % 2 == 0):
        return sumArray(arr, n)
    if (i != 0 and abs(arr[i]) >= abs(arr[i - 1])):
        i -= 1
    arr[i] *= -1
    return sumArray(arr, n)


n = 5
k = 4
arr = [-3, -2, -1, 5, 6]
print(maximizeSum(arr, n, k))

# Expected output:
15
# bin packing problem ( minimize number of used bins ) | returns number of bins required using first fit online algorithm ; initialize result ( count of bins ) ; create an array to store remaining space in bins there can be at most n bins ; place items one by one ; find the first bin that can accommodate weight [ i ] ; if no bin could accommodate weight [ i ] ; 
def firstFit(weight, n, c):
    res = 0
    bin_rem = [0] * n
    for i in range(n):
        j = 0
        while (j < res):
            if (bin_rem[j] >= weight[i]):
                bin_rem[j] = bin_rem[j] - weight[i]
                break
            j += 1
        if (j == res):
            bin_rem[res] = c - weight[i]
            res = res + 1
    return res


weight = [2, 5, 4, 7, 1, 3, 8]
c = 10
n = len(weight)
print("Number of bins required in First Fit : ", firstFit(weight, n, c))

# Expected output:
Number of bins required in First Fit :  4
# maximize count of indices with same element by pairing rows from given matrices | function to find the maximum defined score ; if all students are assigned ; check if row is not paired yet ; check for all indexes ; if values at current indexes are same increase cursum ; further recursive call ; store the ans for current mask and return ; utility function to find the maximum defined score ; create a mask with all set bits 1 -> row is not paired yet 0 -> row is already paired ; initialise dp array with - 1 ; 
def maxScoreSum(a, b, row, mask, dp):
    if (row >= len(a)):
        return 0
    if (dp[mask] != -1):
        return dp[mask]
    ans = 0
    for i in range(len(a)):
        if (mask & (1 << i)):
            newMask = mask ^ (1 << i)
            curSum = 0
            for j in range(len(a[i])):
                if (a[row][j] == b[i][j]):
                    curSum += 1
            ans = max(ans, curSum + maxScoreSum(a, b, row + 1, newMask, dp))
    dp[mask] = ans
    return dp[mask]


def maxScoreSumUtil(a, b, N, M):
    row = 0
    mask = pow(2, M) - 1
    dp = [-1] * (mask + 1)
    return maxScoreSum(a, b, row, mask, dp)


if __name__ == "__main__":
    N = 3
    M = 3
    a = [[1, 1, 0], [1, 0, 1], [0, 0, 1]]
    b = [[1, 0, 0], [0, 0, 1], [1, 1, 0]]
    print(maxScoreSumUtil(a, b, N, M))

# Expected output:
8
# split given arrays into subarrays to maximize the sum of maximum and minimum in each subarrays | function to find the maximum sum of differences of subarrays by splitting array into non - overlapping subarrays ; stores the answer for prefix and initialize with zero ; assume i - th index as right endpoint ; choose the current value as the maximum and minimum ; find the left endpoint and update the array dp [ ] ; return answer ; 
def maxDiffSum(arr, n):
    dp = [0] * n
    for i in range(n):
        maxVal = arr[i]
        minVal = arr[i]
        for j in range(i, -1, -1):
            minVal = min(minVal, arr[j])
            maxVal = max(maxVal, arr[j])
            if (j - 1 >= 0):
                dp[i] = max(dp[i], maxVal - minVal + dp[j - 1])
            else:
                dp[i] = max(dp[i], maxVal - minVal)
    return dp[n - 1]


arr = [8, 1, 7, 9, 2]
N = len(arr)
print(maxDiffSum(arr, N))

# Expected output:
14
# count of n | python 3 program for the above approach ; find the value of x raised to the yth power modulo mod ; stores the value of x ^ y ; iterate until y is positive ; function to perform the modular multiplicative inverse using the fermat 's little theorem ; modular division x / y , find modular multiplicative inverse of y and multiply by x ; function to find binomial coefficient c ( n , k ) in o ( k ) time ; base case ; update the value of p and q ; function to find the count of arrays having k as the first element satisfying the given criteria ; stores the resultant count of arrays ; find the factorization of k ; stores the count of the exponent of the currentprime factor ; n is one last prime factor , for c = 1 -> c ( n - 1 + 1 , 1 ) = n ; return the totol count ; 

from math import sqrt
MOD = 1000000007


def modPow(x, y):
    r = 1
    a = x
    while (y > 0):
        if ((y & 1) == 1):
            r = (r * a) % MOD
        a = (a * a) % MOD
        y /= 2
    return r


def modInverse(x):
    return modPow(x, MOD - 2)


def modDivision(p, q):
    return (p * modInverse(q)) % MOD


def C(n, k):
    if (k > n):
        return 0
    p = 1
    q = 1
    for i in range(1, k + 1, 1):
        q = (q * i) % MOD
        p = (p * (n - i + 1)) % MOD
    return modDivision(p, q)


def countArrays(N, K):
    res = 1
    for p in range(2, int(sqrt(K)), 1):
        c = 0
        while (K % p == 0):
            K /= p
            c += 1
        res = (res * C(N - 1 + c, c)) % MOD
    if (N > 1):
        res = (res * N) % MOD
    return res


if __name__ == '__main__':
    N = 3
    K = 5
    print(countArrays(N, K))

# Expected output:
3
# minimum number of days to debug all programs | python 3 program for the above approach ; function to calculate the minimum work sessions ; break condition ; all bits are set ; check if already calculated ; store the answer ; check if ith bit is set or unset ; including in current work session ; including in next work session ; resultant answer will be minimum of both ; function to initialize dp array and solve the problem ; initialize dp table with - 1 ; resultant mask ; no . of minimum work sessions is even ; no . of minimum work sessions is odd ; 

import sys


def minSessions(codeTime, dp, ones, n, mask, currTime, WorkingSessionTime):
    if (currTime > WorkingSessionTime):
        return sys .maxsize
    if (mask == ones):
        return 1
    if (dp[mask][currTime] != -1):
        return dp[mask][currTime]
    ans = sys .maxsize
    for i in range(n):
        if ((mask & (1 << i)) == 0):
            inc = minSessions(
                codeTime,
                dp,
                ones,
                n,
                mask | (
                    1 << i),
                currTime +
                codeTime[i],
                WorkingSessionTime)
            inc_next = 1 + minSessions(codeTime,
                                       dp,
                                       ones,
                                       n,
                                       mask | (1 << i),
                                       codeTime[i],
                                       WorkingSessionTime)
            ans = min([ans, inc, inc_next])
    dp[mask][currTime] = ans
    return ans


def solve(codeTime, n, WorkingSessionTime):
    dp = [[-1 for i in range(15)]for j in range(1 << 14)]
    ones = (1 << n) - 1
    ans = minSessions(codeTime, dp, ones, n, 0, 0, WorkingSessionTime)
    if (WorkingSessionTime < 6):
        if (ans % 2 == 0):
            ans = ans // 2
        else:
            ans = (ans / 2) + 1
    return int(ans)


if __name__ == '__main__':
    codeTime = [1, 2, 3, 1, 1, 3]
    n = len(codeTime)
    WorkingSessionTime = 4
    print(solve(codeTime, n, WorkingSessionTime))

# Expected output:
2
# count of non | python 3 program for the above approach ; define the dp table globally ; recursive function to calculate total number of valid non - decreasing strings ; if already calculated state ; base case ; stores the total count of strings formed ; fill the value in dp matrix ; function to find the total number of non - decreasing string formed by replacing the '? ; initialize all value of dp table with - 1 ; left and right limits ; iterate through all the characters of the string s ; change r to the current character ; call the recursive function ; change l to r and r to 9 ; reinitialize the length of ? to 0 ; increment the length of the segment ; update the ans ; return the total count ; 

MAXN = 100005
dp = [[-1 for x in range(10)]for y in range(MAXN)]


def solve(len, gap):
    if (dp[len][gap] != -1):
        return dp[len][gap]
    if (len == 0 or gap == 0):
        return 1
    if (gap < 0):
        return 0
    ans = 0
    for i in range(gap + 1):
        ans += solve(len - 1, gap - i)
    dp[len][gap] = ans
    return dp[len][gap]


def countValidStrings(S):
    global dp
    N = len(S)
    L, R = 1, 9
    cnt = 0
    ans = 1
    for i in range(N):
        if (S[i] != '?'):
            R = ord(S[i]) - ord('0')
            ans *= solve(cnt, R - L)
            L = R
            R = 9
            cnt = 0
        else:
            cnt += 1
    ans *= solve(cnt, R - L)
    return ans


if __name__ == "__main__":
    S = "1???2"
    print(countValidStrings(S))

# Expected output:
4
# count of binary arrays of size n with sum of product of adjacent pairs equal to k | function to return the number of total possible combinations of 0 and 1 to form an array of size n having sum of product of consecutive elements k ; if value is greater than k , then return 0 as no combination is possible to have sum k ; check if the result of this recursive call is memoised already , if it is then just return the previously calculated result ; check if the value is equal to k at n , if it is then return 1 as this combination is possible . otherwise return 0. ; if previous element is 1 ; if current element is 1 as well , then add 1 to value ; if current element is 0 , then value will remain same ; if previous element is 0 , then value will remain same irrespective of the current element ; memoise and return the ans ; 
def combinationsPossible(N, idx, prev, val, K, dp):
    if (val > K):
        return 0
    if (dp[val][idx][prev] != -1):
        return dp[val][idx][prev]
    if (idx == N - 1):
        if (val == K):
            return 1
        return 0
    ans = 0
    if (prev == 1):
        ans += combinationsPossible(N, idx + 1, 1, val + 1, K, dp)
        ans += combinationsPossible(N, idx + 1, 0, val, K, dp)
    else:
        ans += combinationsPossible(N, idx + 1, 1, val, K, dp)
        ans += combinationsPossible(N, idx + 1, 0, val, K, dp)
    dp[val][idx][prev] = ans
    return ans


if __name__ == '__main__':
    N = 5
    K = 3
    dp = [[[-1 for i in range(2)]for j in range(N + 1)]for k in range(K + 1)]
    print(
        combinationsPossible(
            N,
            0,
            0,
            0,
            K,
            dp) +
        combinationsPossible(
            N,
            0,
            1,
            0,
            K,
            dp))

# Expected output:
2
# count ways to split an array into subarrays such that sum of the i | python3 program for the above approach ; function to count ways to split an array into subarrays such that sum of the i - th subarray is divisible by i ; stores the prefix sum of array ; find the prefix sum ; initialize dp [ ] [ ] array ; stores the count of splitting ; iterate over the range [ 0 , n ] ; update the dp table ; if the last index is reached , then add it to the variable ans ; return the possible count of splitting of array into subarrays ; 

import numpy as np


def countOfWays(arr, N):
    pre = [0] * (N + 1)
    for i in range(N):
        pre[i + 1] = pre[i] + arr[i]
    dp = np .zeros((N + 2, N + 2))
    dp[1][0] += 1
    ans = 0
    for i in range(N):
        for j in range(N, 0, -1):
            dp[j + 1][pre[i + 1] % (j + 1)] += dp[j][pre[i + 1] % j]
            if (i == N - 1):
                ans += dp[j][pre[i + 1] % j]
    return ans


if __name__ == "__main__":
    arr = [1, 2, 3, 4]
    N = len(arr)
    print(countOfWays(arr, N))

# Expected output:
3.0
# domino and tromino tiling problem | function to find the total number of ways to tile a 2 * n board using the given types of tile ; if n is less than 3 ; store all dp - states ; base case ; traverse the range [ 2 , n ] ; update the value of dp [ i ] [ 0 ] ; update the value of dp [ i ] [ 1 ] ; update the value of dp [ i ] [ 2 ] ; return the number of ways as the value of dp [ n ] [ 0 ] ; 

MOD = 1e9 + 7


def numTilings(N):
    if (N < 3):
        return N
    dp = [[0] * 3 for i in range(N + 1)]
    dp[0][0] = dp[1][0] = 1
    dp[1][1] = dp[1][2] = 1
    for i in range(2, N + 1):
        dp[i][0] = (dp[i - 1][0] + dp[i - 2][0] +
                    dp[i - 2][1] + dp[i - 2][2]) % MOD
        dp[i][1] = (dp[i - 1][0] + dp[i - 1][2]) % MOD
        dp[i][2] = (dp[i - 1][0] + dp[i - 1][1]) % MOD
    return int(dp[N][0])


N = 3
print(numTilings(N))

# Expected output:
5
# count of n | store the recurring recursive states ; function to find the number of strings of length n such that it is a concatenation it substrings ; single character cant be repeated ; check if this state has been already calculated ; stores the resultant count for the current recursive calls ; iterate over all divisors ; non - repeated = total - repeated ; non - repeated = total - repeated ; store the result for the further calculation ; return resultant count ; 

dp = {}


def countStrings(N):
    if N == 1:
        return 0
    if dp .get(N, -1) != -1:
        return dp[N]
    ret = 0
    for div in range(1, int(N ** .5) + 1):
        if N % div == 0:
            ret += (1 << div) - countStrings(div)
            div2 = N // div
            if div2 != div and div != 1:
                ret += (1 << div2) - countStrings(div2)
    dp[N] = ret
    return ret


N = 6
print(countStrings(N))

# Expected output:
10
# count n | python program for the above approach ; function to count n - digit numbers such that each position is divisible by the digit occurring at that position ; stores the answer . ; iterate from indices 1 to n ; stores count of digits that can be placed at the current index ; iterate from digit 1 to 9 ; if index is divisible by digit ; multiply answer with possible choices ; 

mod = 1000000000 + 7


def countOfNumbers(N):
    ans = 1
    for index in range(1, N + 1):
        choices = 0
        for digit in range(1, 10):
            if (index % digit == 0):
                choices += 1
        ans = (ans * choices) % mod
    print(ans)


N = 5
countOfNumbers(N)

# Expected output:
24