giulio98/xlcost-single-prompt huggingface dataset:
# minimize cost of swapping set bits with unset bits in a given binary string | python program for the above approach ; function to find the minimum cost required to swap every set bit with an unset bit ; stores the indices of set and unset bits of the string s ; traverse the string s ; store the indices ; initialize a dp table of size n1 * n2 ; set unreachable states to inf ; fill the dp table according to the given recurrence relation ; update the value of dp [ i ] [ j ] ; return the minimum cost ; 

INF = 1000000000


def minimumCost(s):
    N = len(s)
    A = []
    B = []
    for i in range(0, N):
        if (s[i] == "1"):
            A .append(i)
        else:
            B .append(i)
    n1 = len(A)
    n2 = len(B)
    dp = [[0 for i in range(n2 + 1)]for j in range(n1 + 1)]
    for i in range(1, n1 + 1):
        dp[i][0] = INF
    for i in range(1, n1 + 1):
        for j in range(1, n2 + 1):
            dp[i][j] = min(dp[i][j - 1], dp[i - 1][j - 1] +
                           abs(A[i - 1] - B[j - 1]))
    return dp[n1][n2]


S = "1010001"
print(minimumCost(S))

# Expected output:
3
# queries to find minimum absolute difference between adjacent array elements in given ranges | python3 program for the above approach ; function to find the minimum difference between adjacent array element over the given range [ l , r ] for q queries ; find the sum of all queries ; left and right boundaries of current range ; print the sum of the current query range ; function to find the minimum absolute difference of adjacent array elements for the given range ; stores the absolute difference of adjacent elements ; find the minimum difference of adjacent elements ; 

MAX = 5000


def minDifference(arr, n, q, m):
    for i in range(m):
        L = q[i][0]
        R = q[i][1]
        ans = MAX
        for i in range(L, R):
            ans = min(ans, arr[i])
        print(ans)


def minimumDifference(arr, q, N, m):
    diff = [0] * N
    for i in range(N - 1):
        diff[i] = abs(arr[i] - arr[i + 1])
    minDifference(diff, N - 1, q, m)


if __name__ == "__main__":
    arr = [2, 6, 1, 8, 3, 4]
    N = len(arr)
    Q = [[0, 3], [1, 5], [4, 5]]
    M = len(Q)
    minimumDifference(arr, Q, N, M)

# Expected output:
4
1
1
# minimum number of flips or swaps of adjacent characters required to make two strings equal | function to count the minimum number of operations required to make strings a and b equal ; stores all dp - states ; iterate rate over the range [ 1 , n ] ; if a [ i - 1 ] equals to b [ i - 1 ] ; assign dp [ i - 1 ] to dp [ i ] ; otherwise ; update dp [ i ] ; if swapping is possible ; update dp [ i ] ; return the minimum number of steps required ; 
def countMinSteps(A, B, N):
    dp = [0] * (N + 1)
    for i in range(1, N + 1):
        if (A[i - 1] == B[i - 1]):
            dp[i] = dp[i - 1]
        else:
            dp[i] = dp[i - 1] + 1
        if (i >= 2 and A[i - 2] == B[i - 1] and A[i - 1] == B[i - 2]):
            dp[i] = min(dp[i], dp[i - 2] + 1)
    return dp[N]


A = "0101"
B = "0011"
N = len(A)
print(countMinSteps(A, B, N))

# Expected output:
1
# count of n | python program for the above approach ; function to find the number of n digit numbers such that at least one digit occurs more than once ; base case ; if repeated is true , then for remaining positions any digit can be placed ; if the current state has already been computed , then return it ; stores the count of number for the current recursive calls ; if n = 1 , 0 can be also placed ; if a digit has occurred for the second time , then set repeated to 1 ; otherwise ; for remaining positions any digit can be placed ; if a digit has occurred for the second time , then set repeated to 1 ; return the resultant count for the current recursive call ; function to count all the n - digit numbers having at least one digit 's occurrence more than once ; function to count all possible number satisfying the given criteria ; 

dp = [[[-1 for i in range(2)]for i in range(1 << 10)]for i in range(50)]


def countOfNumbers(digit, mask, repeated, n):
    global dp
    if (digit == n + 1):
        if (repeated):
            return 1
        return 0
    if (repeated):
        return pow(10, n - digit + 1)
    val = dp[digit][mask][repeated]
    if (val != -1):
        return val
    val = 4
    if (digit == 1):
        for i in range((0 if (n == 1)else 1), 10):
            if (mask & (1 << i)):
                val += countOfNumbers(digit + 1, mask | (1 << i), 1, n)
        else:
            val += countOfNumbers(digit + 1, mask | (1 << i), 0, n)
    else:
        for i in range(10):
            if (mask & (1 << i)):
                val += countOfNumbers(digit + 1, mask | (1 << i), 1, n)
        else:
            val += countOfNumbers(digit + 1, mask | (1 << i), 0, n)
    dp[digit][mask][repeated] = val
    return dp[digit][mask][repeated]


def countNDigitNumber(N):
    print(countOfNumbers(1, 0, 0, N))


if __name__ == '__main__':
    N = 2
    countNDigitNumber(N)

# Expected output:
9
# construct the largest number whose sum of cost of digits is k | function to find the maximum number among the two numbers s and t ; if "0" exists in the string s ; if "0" exists in the string t ; else return the maximum number formed ; recursive function to find maximum number formed such that the sum of cost of digits of formed number is k ; base case ; return the stored state ; including the digit ( idx + 1 ) ; excluding the digit ( idx + 1 ) ; store the result and return ; function to find the maximum number formed such that the sum of the cost digits in the formed number is k ; stores all dp - states ; recursive call ; return the result ; 
def getMaximum(S, T):
    if (S .count("0") > 0):
        return T
    if (T .count("0") > 0):
        return S
    return S if len(S) > len(T)else T


def recursion(arr, idx, N, K, dp):
    if (K == 0):
        return ""
    if (K < 0 or idx == N):
        return "0"
    if (dp[idx][K] != "-1"):
        return dp[idx][K]
    include = str(idx + 1) + recursion(arr, 0, N, K - arr[idx], dp)
    exclude = recursion(arr, idx + 1, N, K, dp)
    dp[idx][K] = getMaximum(include, exclude)
    return (dp[idx][K])


def largestNumber(arr, N, K):
    dp = [["-1"for i in range(K + 1)]for i in range(N + 1)]
    ans = recursion(arr, 0, N, K, dp)
    return "0"if ans == ""else ans


arr = [3, 12, 9, 5, 3, 4, 6, 5, 10]
K = 14
N = len(arr)
print(largestNumber(arr, N, K))

# Expected output:
8555
# count of n | python3 program for the above approach ; function to calculate count of ' n ' digit numbers such that bitwise and of adjacent digits is 0. ; if digit = n + 1 , a valid n - digit number has been formed ; if the state has already been computed ; if current position is 1 , then any digit from [ 1 - 9 ] can be placed . if n = 1 , 0 can be also placed . ; for remaining positions , any digit from [ 0 - 9 ] can be placed after checking the conditions . ; check if bitwise and of current digit and previous digit is 0. ; return answer ; 

dp = [[-1 for i in range(10)]for j in range(100)]
val = 0


def countOfNumbers(digit, prev, n):
    global val
    global dp
    if (digit == n + 1):
        return 1
    val = dp[digit][prev]
    if (val != -1):
        return val
    val = 0
    if (digit == 1):
        i = 0 if n == 1 else 1
        while (i <= 9):
            val += countOfNumbers(digit + 1, i, n)
            i += 1
    else:
        for i in range(10):
            if ((i & prev) == 0):
                val += countOfNumbers(digit + 1, i, n)
    return val


if __name__ == '__main__':
    N = 3
    print(countOfNumbers(1, 0, N))

# Expected output:
264
# number of ways such that only k bars are visible from the left | dp array ; function to calculate the number of permutations of n , where only k bars are visible from the left . ; if subproblem has already been calculated , return ; only ascending order is possible ; n is placed at the first position the nest n - 1 are arranged in ( n - 1 ) ! ways ; recursing ; 

dp = [[0 for i in range(1005)]for j in range(1005)]


def KvisibleFromLeft(N, K):
    if (dp[N][K] != -1):
        return dp[N][K]
    if (N == K):
        dp[N][K] = 1
        return dp[N][K]
    if (K == 1):
        ans = 1
        for i in range(1, N):
            ans *= i
        dp[N][K] = ans
        return dp[N][K]
    dp[N][K] = KvisibleFromLeft(N - 1, K - 1) + \
        (N - 1) * KvisibleFromLeft(N - 1, K)
    return dp[N][K]


N, K = 5, 2
for i in range(1005):
    for j in range(1005):
        dp[i][j] = -1
print(KvisibleFromLeft(N, K))

# Expected output:
50
# number of distinct words of size n with at most k contiguous vowels | power function to calculate long powers with mod ; function for finding number of ways to create string with length n and atmost k contiguous vowels ; array dp to store number of ways ; dp [ i ] [ 0 ] = ( dp [ i - 1 ] [ 0 ] + dp [ i - 1 ] [ 1 ] . . dp [ i - 1 ] [ k ] ) * 21 ; now setting sum to be dp [ i ] [ 0 ] ; if j > i , no ways are possible to create a string with length i and vowel j ; if j = i all the character should be vowel ; dp [ i ] [ j ] relation with dp [ i - 1 ] [ j - 1 ] ; adding dp [ i ] [ j ] in the sum ; 
def power(x, y, p):
    res = 1
    x = x % p
    if (x == 0):
        return 0
    while (y > 0):
        if (y & 1):
            res = (res * x) % p
        y = y >> 1
        x = (x * x) % p
    return res


def kvowelwords(N, K):
    i, j = 0, 0
    MOD = 1000000007
    dp = [[0 for i in range(K + 1)]for i in range(N + 1)]
    sum = 1
    for i in range(1, N + 1):
        dp[i][0] = sum * 21
        dp[i][0] %= MOD
        sum = dp[i][0]
        for j in range(1, K + 1):
            if (j > i):
                dp[i][j] = 0
            elif (j == i):
                dp[i][j] = power(5, i, MOD)
            else:
                dp[i][j] = dp[i - 1][j - 1] * 5
            dp[i][j] %= MOD
            sum += dp[i][j]
            sum %= MOD
    return sum


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

# Expected output:
17576
# maximize the length of upper boundary formed by placing given n rectangles horizontally or vertically | function to find maximum length of the upper boundary formed by placing each of the rectangles either horizontally or vertically ; stores the intermediate transition states ; place the first rectangle horizontally ; place the first rectangle vertically ; place horizontally ; stores the difference in height of current and previous rectangle ; take maximum out of two options ; place vertically ; stores the difference in height of current and previous rectangle ; take maximum out two options ; print maximum of horizontal or vertical alignment of the last rectangle ; 
def maxBoundary(N, V):
    dp = [[0 for i in range(2)]for j in range(N)]
    dp[0][0] = V[0][0]
    dp[0][1] = V[0][1]
    for i in range(1, N, 1):
        dp[i][0] = V[i][0]
        height1 = abs(V[i - 1][1] - V[i][1])
        height2 = abs(V[i - 1][0] - V[i][1])
        dp[i][0] += max(height1 + dp[i - 1][0], height2 + dp[i - 1][1])
        dp[i][1] = V[i][1]
        vertical1 = abs(V[i][0] - V[i - 1][1])
        vertical2 = abs(V[i][0] - V[i - 1][1])
        dp[i][1] += max(vertical1 + dp[i - 1][0], vertical2 + dp[i - 1][1])
    print(max(dp[N - 1][0], dp[N - 1][1]) - 1)


if __name__ == '__main__':
    N = 5
    V = [[2, 5], [3, 8], [1, 10], [7, 14], [2, 5]]
    maxBoundary(N, V)

# Expected output:
68
# ways to sum to n using natural numbers up to k with repetitions allowed | function to find the total number of ways to represent n as the sum of integers over the range [ 1 , k ] ; initialize a list ; update dp [ 0 ] to 1 ; iterate over the range [ 1 , k + 1 ] ; iterate over the range [ 1 , n + 1 ] ; if col is greater than or equal to row ; update current dp [ col ] state ; return the total number of ways ; 
def NumberOfways(N, K):
    dp = [0] * (N + 1)
    dp[0] = 1
    for row in range(1, K + 1):
        for col in range(1, N + 1):
            if (col >= row):
                dp[col] = dp[col] + dp[col - row]
    return (dp[N])


N = 8
K = 2
print(NumberOfways(N, K))

# Expected output:
5
# queries to check if array elements from indices [ l , r ] forms an arithmetic progression or not | function to check if the given range of queries form an ap or not in the given array arr [ ] ; stores length of the longest subarray forming ap for every array element ; iterate over the range [ 0 , n ] ; stores the index of the last element of forming ap ; iterate until the element at index ( j , j + 1 ) forms ap ; increment j by 1 ; traverse the current subarray over the range [ i , j - 1 ] ; update the length of the longest subarray at index k ; update the value of i ; traverse the given queries ; print the result ; otherwise ; 
def findAPSequence(arr, N, Q, M):
    dp = [0] * (N + 5)
    i = 0
    while i + 1 < N:
        j = i + 1
        while (j + 1 < N and arr[j + 1] - arr[j] == arr[i + 1] - arr[i]):
            j += 1
        for k in range(i, j):
            dp[k] = j - k
        i = j
    for i in range(M):
        if (dp[Q[i][0]] >= Q[i][1] - Q[i][0]):
            print("Yes")
        else:
            print("No")


if __name__ == "__main__":
    arr = [1, 3, 5, 7, 6, 5, 4, 1]
    Q = [[0, 3], [3, 4], [2, 4]]
    N = len(arr)
    M = len(Q)
    findAPSequence(arr, N, Q, M)

# Expected output:
Yes
Yes
No
# minimize difference between sum of two k | python3 program for the above approach ; stores the values at recursive states ; function to find the minimum difference between sum of two k - length subsets ; base case ; if k1 and k2 are 0 , then return the absolute difference between sum1 and sum2 ; otherwise , return int_max ; if the result is already computed , return the result ; store the 3 options ; including the element in first subset ; including the element in second subset ; not including the current element in both the subsets ; store minimum of 3 values obtained ; return the value for the current states ; 

import sys
dp = [[[-1 for i in range(100)]for i in range(100)]for i in range(100)]


def minSumDifference(arr, n, k1, k2, sum1, sum2):
    global dp
    if (n < 0):
        if (k1 == 0 and k2 == 0):
            return abs(sum1 - sum2)
        else:
            return sys .maxsize + 1
    if (dp[n][sum1][sum2] != -1):
        return dp[n][sum1][sum2]
    op1 = sys .maxsize + 1
    op2 = sys .maxsize + 1
    op3 = sys .maxsize + 1
    if (k1 > 0):
        op1 = minSumDifference(arr, n - 1, k1 - 1, k2, sum1 + arr[n], sum2)
    if (k2 > 0):
        op2 = minSumDifference(arr, n - 1, k1, k2 - 1, sum1, sum2 + arr[n])
    op3 = minSumDifference(arr, n - 1, k1, k2, sum1, sum2)
    dp[n][sum1][sum2] = min(op1, min(op2, op3))
    return dp[n][sum1][sum2]


if __name__ == '__main__':
    arr = [12, 3, 5, 6, 7, 17]
    K = 2
    N = len(arr)
    print(minSumDifference(arr, N - 1, K, K, 0, 0))

# Expected output:
1
# geek | function to calculate the n - th geek - onacci number ; stores the geekonacci series ; store the first three terms of the series ; iterate over the range [ 3 , n ] ; update the value of arr [ i ] as the sum of previous 3 terms in the series ; return the last element of arr [ ] as the n - th term ; 
def find(A, B, C, N):
    arr = [0] * N
    arr[0] = A
    arr[1] = B
    arr[2] = C
    for i in range(3, N):
        arr[i] = (arr[i - 1] + arr[i - 2] + arr[i - 3])
    return arr[N - 1]


A = 1
B = 3
C = 2
N = 4
print(find(A, B, C, N))

# Expected output:
6
# maximum sum subsequence made up of at most k distant elements including the first and last array elements | python program for the above approach ;  ; function to find maximum sum of a subsequence satisfying the given conditions ; stores the maximum sum ; starting index of the subsequence ; stores the pair of maximum value and the index of that value ; traverse the array ; increment the first value of deque by arr [ i ] and store it in dp [ i ] ; delete all the values which are less than dp [ i ] in deque ; append the current pair of value and index in deque ; if first value of the queue is at a distance > k ; return the value at the last index ; 

from collections import deque


def maxResult(arr, k):
    dp = [0] * len(arr)
    dp[0] = arr[0]
    q = deque([(arr[0], 0)])
    for i in range(1, len(arr)):
        dp[i] = arr[i] + q[0][0]
        while q and q[-1][0] < dp[i]:
            q .pop()
        q .append((dp[i], i))
        if i - k == q[0][1]:
            q .popleft()
    return dp[-1]


arr = [10, -5, -2, 4, 0, 3]
K = 3
print(maxResult(arr, K))

# Expected output:
17
# minimum days required to cure n persons | function to find minimum count of days required to give a cure such that the high risk person and risk person does not get a dose on same day . ; stores count of persons whose age is less than or equal to 10 and greater than or equal to 60. ; stores the count of persons whose age is in the range [ 11 , 59 ] ; traverse the array arr [ ] ; if age less than or equal to 10 or greater than or equal to 60 ; update risk ; update normal_risk ; calculate days to cure risk and normal_risk persons ; prthe days ; 
def daysToCure(arr, N, P):
    risk = 0
    normal_risk = 0
    for i in range(N):
        if (arr[i] >= 60 or arr[i] <= 10):
            risk += 1
        else:
            normal_risk += 1
    days = (risk // P) + (risk %
                          P > 0) + (normal_risk // P) + (normal_risk %
                                                         P > 0)
    print(days)


if __name__ == '__main__':
    arr = [9, 80, 27, 72, 79]
    N = len(arr)
    P = 2
    daysToCure(arr, N, P)

# Expected output:
3
# count numbers from a given range whose product of digits is k | python 3 program to implement the above approach ; function to count numbers in the range [ 0 , x ] whose product of digit is k ; if count of digits in a number greater than count of digits in x ; if product of digits of a number equal to k ; if overlapping subproblems already occurred ; stores count of numbers whose product of digits is k ; check if the numbers exceeds k or not ; iterate over all possible value of i - th digits ; if number contains leading 0 ; update res ; update res ; return res ; utility function to count the numbers in the range [ l , r ] whose prod of digits is k ; stores numbers in the form of string ; stores overlapping subproblems ; stores count of numbers in the range [ 0 , r ] whose product of digits is k ; update str ; stores count of numbers in ; the range [ 0 , l - 1 ] whose product of digits is k ; 

M = 100


def cntNum(X, i, prod, K, st, tight, dp):
    end = 0
    if (i >= len(X) or prod > K):
        if (prod == K):
            return 1
        else:
            return 0
    if (dp[prod][i][tight][st] != -1):
        return dp[prod][i][tight][st]
    res = 0
    if (tight != 0):
        end = ord(X[i]) - ord('0')
    for j in range(end + 1):
        if (j == 0 and st == 0):
            res += cntNum(X, i + 1, prod, K, False, (tight & (j == end)), dp)

        else:
            res += cntNum(X, i + 1, prod * j, K, True,
                          (tight & (j == end)), dp)

    dp[prod][i][tight][st] = res
    return res


def UtilCntNumRange(L, R, K):
    global M
    str1 = str(R)
    dp = [[[[-1 for i in range(2)] for j in range(2)]
           for k in range(M)] for l in range(M)]
    cntR = cntNum(str1, 0, 1, K, False, True, dp)
    str1 = str(L - 1)
    dp = [[[[-1 for i in range(2)] for j in range(2)]
           for k in range(M)] for l in range(M)]
    cntR = 20
    cntL = cntNum(str1, 0, 1, K, False, True, dp)
    return (cntR - cntL)


if __name__ == '__main__':
    L = 20
    R = 10000
    K = 14
    print(UtilCntNumRange(L, R, K))

# Expected output:
20
# count all possible n | function to find the number of vowel permutations possible ; to avoid the large output value ; initialize 2d dp array ; initialize dp [ 1 ] [ i ] as 1 since string of length 1 will consist of only one vowel in the string ; directed graph using the adjacency matrix ; iterate over the range [ 1 , n ] ; traverse the directed graph ; traversing the list ; update dp [ i + 1 ] [ u ] ; stores total count of permutations ; return count of permutations ; 
def countVowelPermutation(n):
    MOD = 1e9 + 7
    dp = [[0 for i in range(5)]for j in range(n + 1)]
    for i in range(5):
        dp[1][i] = 1
    relation = [[1], [0, 2], [0, 1, 3, 4], [2, 4], [0]]
    for i in range(1, n, 1):
        for u in range(5):
            dp[i + 1][u] = 0
            for v in relation[u]:
                dp[i + 1][u] += dp[i][v] % MOD
    ans = 0
    for i in range(5):
        ans = (ans + dp[n][i]) % MOD
    return int(ans)


if __name__ == '__main__':
    N = 2
    print(countVowelPermutation(N))

# Expected output:
10
# queries to calculate bitwise or of each subtree of a given node in an n | maximum number of nodes ; adjacency list ; stores bitwise or of each node ; function to add edges to the tree ; traverse the edges ; add edges ; function to perform dfs traversal on the given tree ; initialize answer with bitwise or of current node ; iterate over each child of the current node ; skip parent node ; call dfs for each child ; taking bitwise or of the answer of the child to find node 's or value ; function to call dfs from the '= root for precomputing answers ; function to calculate and print the bitwise or for q queries ; perform preprocessing ; iterate over each given query ; utility function to find and print bitwise or for q queries ; function to add edges to graph ; function call ; 

N = 100005
adj = [[]for i in range(N)]
answer = [0 for i in range(N)]


def addEdgesToGraph(Edges, N):
    for i in range(N - 1):
        u = Edges[i][0]
        v = Edges[i][1]
        adj[u].append(v)
        adj[v].append(u)


def DFS(node, parent, Val):
    answer[node] = Val[node]
    for child in adj[node]:
        if (child == parent):
            continue
        DFS(child, node, Val)
        answer[node] = (answer[node] | answer[child])


def preprocess(Val):
    DFS(1, -1, Val)


def findSubtreeOR(Queries, Q, Val):
    preprocess(Val)
    for i in range(Q):
        print(answer[Queries[i]], end=' ')


def findSubtreeORUtil(N, Edges, Val, Queries, Q):
    addEdgesToGraph(Edges, N)
    findSubtreeOR(Queries, Q, Val)


if __name__ == '__main__':
    N = 5
    Edges = [[1, 2], [1, 3], [3, 4], [3, 5]]
    Val = [0, 2, 3, 4, 8, 16]
    Queries = [2, 3, 1]
    Q = len(Queries)
    findSubtreeORUtil(N, Edges, Val, Queries, Q)

# Expected output:
3 28 31
# maximize sum of k elements selected from a matrix such that each selected element must be preceded by selected row elements | python program for the above approach ; function to return the maximum of two elements ; function to find the maximum sum of selecting k elements from the given 2d array arr ; dp table of size ( k + 1 ) * ( n + 1 ) ; initialize dp [ 0 ] [ i ] = 0 ; initialize dp [ i ] [ 0 ] = 0 ; selecting i elements ; select i elements till jth row ; sum = 0 , to keep track of cummulative elements sum ; traverse arr [ j ] [ k ] until number of elements until k > i ; select arr [ j ] [ k - 1 ] th item ; store the maxsum in dp [ i ] [ j + 1 ] ; return the maximum sum ; 

import math


def max(a, b):
    if (a > b):
        return a
    else:
        return b


def maximumsum(arr, K, N, M):
    sum = 0
    maxSum = 0
    dp = [[0 for i in range(N + 1)]for j in range(K + 1)]
    for i in range(0, N + 1):
        dp[0][i] = 0
    for i in range(0, K + 1):
        dp[i][0] = 0
    for i in range(1, K + 1):
        for j in range(0, N):
            sum = 0
            maxSum = dp[i][j]
            for k in range(1, i + 1):
                if (k > M):
                    break
                sum += arr[j][k - 1]
                maxSum = max(maxSum, sum + dp[i - k][j])
            dp[i][j + 1] = maxSum
    return dp[K][N]


if __name__ == '__main__':
    arr = [[10, 10, 100, 30], [80, 50, 10, 50]]
    N = 2
    M = 4
    K = 5
    print(maximumsum(arr, K, N, M))

# Expected output:
250