giulio98/xlcost-single-prompt huggingface dataset:
# maximize sum by selecting x different | python3 program for the above approach ; store overlapping subproblems of the recurrence relation ; function to find maximum sum of at most n with different index array elements such that at most x are from a [ ] , y are from b [ ] and z are from c [ ] ; base cases ; if the subproblem already computed ; selecting i - th element from a [ ] ; selecting i - th element from b [ ] ; selecting i - th element from c [ ] ; i - th elements not selected from any of the arrays ; select the maximum sum from all the possible calls ; 

import sys
dp = [[[[-1 for i in range(50)]for j in range(50)]
       for k in range(50)]for l in range(50)]


def FindMaxS(X, Y, Z, n, A, B, C):
    if (X < 0 or Y < 0 or Z < 0):
        return -sys .maxsize - 1
    if (n < 0):
        return 0
    if (dp[n][X][Y][Z] != -1):
        return dp[n][X][Y][Z]
    ch = A[n] + FindMaxS(X - 1, Y, Z, n - 1, A, B, C)
    ca = B[n] + FindMaxS(X, Y - 1, Z, n - 1, A, B, C)
    co = C[n] + FindMaxS(X, Y, Z - 1, n - 1, A, B, C)
    no = FindMaxS(X, Y, Z, n - 1, A, B, C)
    maximum = max(ch, max(ca, max(co, no)))
    dp[n][X][Y][Z] = maximum
    return dp[n][X][Y][Z]


if __name__ == '__main__':
    X = 1
    Y = 1
    Z = 1
    A = [10, 0, 5]
    B = [5, 10, 0]
    C = [0, 5, 10]
    n = len(B)
    print(FindMaxS(X, Y, Z, n - 1, A, B, C))

# Expected output:
30
# minimize swaps of adjacent characters to sort every possible rearrangement of given binary string | python3 program for the above approach ; precalculate the values of power of 2 ; function to calculate 2 ^ n % mod ; function to find sum of inversions ; initialise a list of 0 s and ? s ; traverse the string in the reversed manner ; if the current character is 1 ; effectively calculate a * b ^ ( b - 1 ) ; if the current character is 0 ; increment count of zeroes ; double count the zeroes ; find b * 2 ^ ( b - 1 ) ; increment count of questions ; return the final count ; 

MOD = 10 ** 9 + 7
MEM = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]


def mod_pow2(n):
    while n >= len(MEM):
        MEM .append((MEM[-1] * 2) % MOD)
    return MEM[n]


def inversions(bstr):
    total, zeros, questions = (0,) * 3
    for x in reversed(bstr):
        if x == '1':
            z = zeros * mod_pow2(questions)
            if questions == 0:
                q = 0
            else:
                q = questions * mod_pow2(questions - 1)
            total = (total + z + q) % MOD
        elif x == '0':
            zeros += 1
        else:
            total *= 2
            z = zeros * mod_pow2(questions)
            if questions == 0:
                q = 0
            else:
                q = questions * mod_pow2(questions - 1)
            total = (total + z + q) % MOD
            questions += 1
    return total


def main():
    S = "?0?"
    print(inversions(S))


if __name__ == "__main__":
    main()

# Expected output:
3
# minimum removals required to convert given array to a mountain array | utility function to count array elements required to be removed to make array a mountain array ; stores length of increasing subsequence from [ 0 , i - 1 ] ; stores length of increasing subsequence from [ i + 1 , n - 1 ] ; iterate for each position up to n - 1 to find the length of subsequence ; if j is less than i , then i - th position has leftincreasing [ j ] + 1 lesser elements including itself ; check if it is the maximum obtained so far ; search for increasing subsequence from right ; find the position following the peak condition and have maximum leftincreasing [ i ] + rightincreasing [ i ] ; function to count elements to be removed to make array a mountain array ; print the answer ; 
def minRemovalsUtil(arr):
    result = 0
    if (len(arr) < 3):
        return -1
    leftIncreasing = [0] * len(arr)
    rightIncreasing = [0] * len(arr)
    for i in range(1, len(arr)):
        for j in range(i):
            if (arr[j] < arr[i]):
                leftIncreasing[i] = max(
                    leftIncreasing[i], leftIncreasing[j] + 1)
    for i in range(len(arr) - 2, -1, -1):
        j = len(arr) - 1
        while j > i:
            if (arr[j] < arr[i]):
                rightIncreasing[i] = max(
                    rightIncreasing[i], rightIncreasing[j] + 1)
            j -= 1
    for i in range(len(arr)):
        if (leftIncreasing[i] != 0 and rightIncreasing[i] != 0):
            result = max(result, leftIncreasing[i] + rightIncreasing[i])
    return len(arr) - (result + 1)


def minRemovals(arr):
    ans = minRemovalsUtil(arr)
    print(ans)


if __name__ == "__main__":
    arr = [2, 1, 1, 5, 6, 2, 3, 1]
    minRemovals(arr)

# Expected output:
3
# minimum number of jumps to obtain an element of opposite parity | bfs for odd numbers are source ; initialize queue ; stores for each node , the nodes visited and their distances ; if parity is 0 -> odd otherwise -> even ; perform multi - source bfs ; extract the front element of the queue ; traverse nodes connected to the current node ; if u is not visited ; if element with opposite parity is obtained ; store its distance from source in ans [ ] ; push the current neighbour to the queue ; function to find the minimum jumps required by each index to reach element of opposite parity ; initialise inverse graph ; stores the result for each index ; for the jumped index ; if the ind is valid then add reverse directed edge ; multi - source bfs with odd numbers as source by passing 0 ; multi - source bfs with even numbers as source by passing 1 ; print the answer ; 
def bfs(n, a, invGr, ans, parity):
    q = []
    vis = [0 for i in range(n + 1)]
    dist = [0 for i in range(n + 1)]
    for i in range(1, n + 1):
        if ((a[i] + parity) & 1):
            q .append(i)
            vis[i] = 1
    while (len(q) != 0):
        v = q[0]
        q .pop(0)
        for u in invGr[v]:
            if (not vis[u]):
                dist[u] = dist[v] + 1
                vis[u] = 1
                if ((a[u] + parity) % 2 == 0):
                    if (ans[u] == -1):
                        ans[u] = dist[u]
                q .append(u)


def minJumps(a, jump, n):
    invGr = [[]for i in range(n + 1)]
    ans = [-1 for i in range(n + 1)]
    for i in range(1, n + 1):
        for ind in [i + jump[i], i - jump[i]]:
            if (ind >= 1 and ind <= n):
                invGr[ind].append(i)
    bfs(n, a, invGr, ans, 0)
    bfs(n, a, invGr, ans, 1)
    for i in range(1, n + 1):
        print(str(ans[i]), end=' ')


if __name__ == '__main__':
    arr = [0, 4, 2, 5, 2, 1]
    jump = [0, 1, 2, 3, 1, 2]
    N = len(arr)
    minJumps(arr, jump, N - 1)

# Expected output:
3 2 -1 1 -1
# count unique paths is a matrix whose product of elements contains odd number of divisors | python3 program for the above approach ; stores the results ; count of unique product paths ; function to check whether number is perfect square or not ; if square root is an integer ; function to calculate and store all the paths product in vector ; store the value a [ 0 ] [ 0 ] ; initialize first row of dp ; find prefix product ; initialize first column of dp ; find the prefix product ; iterate over range ( 1 , 1 ) to ( n , m ) ; copy dp [ i - 1 ] [ j ] in top [ ] ; copy dp [ i ] [ j - 1 ] into left [ ] ; compute the values of current state and store it in curr [ ] ; find the product of a [ i ] [ j ] with elements at top [ ] ; find the product of a [ i ] [ j ] with elements at left [ ] ; update the current state ; traverse dp [ m - 1 ] [ n - 1 ] ; check if perfect square ; 

from math import sqrt, floor
dp = [[[]for j in range(105)]for k in range(105)]
countPaths = 0


def isPerfectSquare(n):
    sr = sqrt(n)
    return ((sr - floor(sr)) == 0)


def countUniquePaths(a, m, n, ans):
    global dp
    global countPaths
    dp[0][0].append(a[0][0])
    for i in range(1, m):
        a[i][0] *= a[i - 1][0]
        dp[i][0].append(a[i][0])
    for i in range(1, n):
        a[0][i] *= a[0][i - 1]
        dp[0][i].append(a[0][i])
    for i in range(1, m):
        for j in range(1, n):
            top = dp[i - 1][j]
            left = dp[i][j - 1]
            curr = []
            for k in range(len(top)):
                curr .append(top[k] * a[i][j])
            for k in range(len(left)):
                curr .append(left[k] * a[i][j])
            dp[i][j] = curr
    for i in dp[m - 1][n - 1]:
        if (isPerfectSquare(i)):
            countPaths += 1


if __name__ == '__main__':
    M = 3
    N = 4
    mat = [[1, 2, 3, 1], [3, 1, 2, 4], [2, 3, 1, 1]]
    countUniquePaths(mat, M, N, 1)
    print(countPaths)

# Expected output:
3
# generate a combination of minimum coins that sums to a given value | python3 program for the above approach ; dp array to memoize the results ; list to store the result ; function to find the minimum number of coins to make the sum equals to x ; base case ; if previously computed subproblem occurred ; initialize result ; try every coin that has smaller value than n ; check for int_max to avoid overflow and see if result . an be minimized ; memoizing value of current state ; function to find the possible combination of coins to make the sum equal to x ; base case ; print solutions ; try every coin that has value smaller than n ; add current denominations ; backtrack ; function to find the minimum combinations of coins for value x ; min coins ; if no solution exists ; backtrack to find the solution ; 

import sys
MAX = 100000
dp = [-1] * (MAX + 1)
denomination = []


def countMinCoins(n, C, m):
    if (n == 0):
        dp[0] = 0
        return 0
    if (dp[n] != -1):
        return dp[n]
    ret = sys .maxsize
    for i in range(m):
        if (C[i] <= n):
            x = countMinCoins(n - C[i], C, m)
            if (x != sys .maxsize):
                ret = min(ret, 1 + x)
    dp[n] = ret
    return ret


def findSolution(n, C, m):
    if (n == 0):
        for it in denomination:
            print(it, end=" ")
        return
    for i in range(m):
        if (n - C[i] >= 0 and dp[n - C[i]] + 1 == dp[n]):
            denomination .append(C[i])
            findSolution(n - C[i], C, m)
            break


def countMinCoinsUtil(X, C, N):
    isPossible = countMinCoins(X, C, N)
    if (isPossible == sys .maxsize):
        print("-1")
    else:
        findSolution(X, C, N)


if __name__ == '__main__':
    X = 21
    arr = [2, 3, 4, 5]
    N = len(arr)
    countMinCoinsUtil(X, arr, N)

# Expected output:
2 4 5 5 5
# count all possible paths from top left to bottom right of a matrix without crossing the diagonal | function to calculate binomial coefficient c ( n , r ) ; c ( n , r ) = c ( n , n - r ) ; [ n * ( n - 1 ) * -- - * ( n - r + 1 ) ] / [ r * ( r - 1 ) * -- -- * 1 ] ; function to calculate the total possible paths ; update n to n - 1 ; stores 2 ncn ; stores nth catalan number ; stores the required answer ; 
def binCoff(n, r):
    val = 1
    if (r > (n - r)):
        r = (n - r)
    for i in range(r):
        val *= (n - i)
        val //= (i + 1)
    return val


def findWays(n):
    n = n - 1
    a = binCoff(2 * n, n)
    b = a // (n + 1)
    ans = b
    return ans


if __name__ == "__main__":
    n = 4
    print(findWays(n))

# Expected output:
5
# minimum operations to transform given string to another by moving characters to front or end | python3 program for the above approach ; function that finds the minimum number of steps to find the minimum characters must be moved to convert string s to t ; r = maximum value over all dp [ i ] [ j ] computed so far ; dp [ i ] [ j ] stores the longest contiguous suffix of t [ 0. . j ] that is subsequence of s [ 0. . i ] ; update the maximum length ; return the resulting length ; 

dp = [[0] * 1010] * 1010


def solve(s, t):
    n = len(s)
    r = 0
    for j in range(0, n):
        for i in range(0, n):
            dp[i][j] = 0
            if (i > 0):
                dp[i][j] = max(dp[i - 1][j], dp[i][j])
            if (s[i] == t[j]):
                ans = 1
                if (i > 0 and j > 0):
                    ans = 1 + dp[i - 1][j - 1]
                dp[i][j] = max(dp[i][j], ans)
                r = max(r, dp[i][j])
    return (n - r)


s = "abcde"
t = "edacb"
print(solve(s, t))

# Expected output:
3
# longest substring whose characters can be rearranged to form a palindrome | function to get the length of longest substring whose characters can be arranged to form a palindromic string ; to keep track of the last index of each xor ; initialize answer with 0 ; now iterate through each character of the string ; convert the character from [ a , z ] to [ 0 , 25 ] ; turn the temp - th bit on if character occurs odd number of times and turn off the temp - th bit off if the character occurs ever number of times ; if a mask is present in the index therefore a palindrome is found from index [ mask ] to i ; if x is not found then add its position in the index dict . ; check for the palindrome of odd length ; we cancel the occurrence of a character if it occurs odd number times ; given string ; length of 
def longestSubstring(s: str, n: int):
    index = dict()
    answer = 0
    mask = 0
    index[mask] = -1
    for i in range(n):
        temp = ord(s[i]) - 97
        mask ^= (1 << temp)
        if mask in index .keys():
            answer = max(answer, i - index[mask])
        else:
            index[mask] = i
        for j in range(26):
            mask2 = mask ^ (1 << j)
            if mask2 in index .keys():
                answer = max(answer, i - index[mask2])
    return answer


s = "adbabd"
n = len(s)
print(longestSubstring(s, n))

# Expected output:
6
# count of n | function to find count of n - digit numbers with single digit xor ; dp [ i ] [ j ] stores the number of i - digit numbers with xor equal to j ; for 1 - 9 store the value ; iterate till n ; calculate xor ; store in dp table ; initialize count ; print answer ; 
def countNums(N):
    dp = [[0 for i in range(16)]for j in range(N)]
    for i in range(1, 10):
        dp[0][i] = 1
    for i in range(1, N):
        for j in range(0, 10):
            for k in range(0, 16):
                xor = j ^ k
                dp[i][xor] += dp[i - 1][k]
    count = 0
    for i in range(0, 10):
        count += dp[N - 1][i]
    print(count)


if __name__ == '__main__':
    N = 1
    countNums(N)

# Expected output:
9
# count of numbers upto m divisible by given prime numbers | function to count the numbers that are divisible by the numbers in the array from range 1 to m ; initialize the count variable ; iterate over [ 1 , m ] ; iterate over array elements arr [ ] ; check if i is divisible by a [ j ] ; increment the count ; return the answer ; given list lst ; 
def count(a, M, N):
    cnt = 0
    for i in range(1, M + 1):
        for j in range(N):
            if (i % a[j] == 0):
                cnt += 1
                break
    return cnt


lst = [2, 3, 5, 7]
m = 100
n = len(lst)
print(count(lst, m, n))

# Expected output:
78
# count of numbers upto n digits formed using digits 0 to k | python3 implementation to count the numbers upto n digits such that no two zeros are adjacent ; function to count the numbers upto n digits such that no two zeros are adjacent ; condition to check if only one element remains ; if last element is non zero , return k - 1 ; if last element is 0 ; condition to check if value calculated already ; if last element is non zero , then two cases arise , current element can be either zero or non zero ; memoize this case ; if last is 0 , then current can only be non zero ; memoize and return ; 

dp = [[0] * 10 for j in range(15)]


def solve(n, last, k):
    if (n == 1):
        if (last == k):
            return (k - 1)
        else:
            return 1
    if (dp[n][last]):
        return dp[n][last]
    if (last == k):
        dp[n][last] = ((k - 1) * solve(n - 1, k, k) +
                       (k - 1) * solve(n - 1, 1, k))
        return dp[n][last]
    else:
        dp[n][last] = solve(n - 1, k, k)
        return dp[n][last]


n = 2
k = 3
x = solve(n, k, k) + solve(n, 1, k)
print(x)

# Expected output:
8
# count of occurrences of each prefix in a string using modified kmp algorithm | function to print the count of all prefix in the given string ; iterate over string s ; print the prefix and their frequency ; function to implement the lps array to store the longest prefix which is also a suffix for every substring of the string s ; array to store lps values value of lps [ 0 ] is 0 by definition ; find the values of lps [ i ] for the rest of the string using two pointers and dp ; initially set the value of j as the longest prefix that is also a suffix for i as lps [ i - 1 ] ; check if the suffix of length j + 1 is also a prefix ; if s [ i ] = s [ j ] then , assign lps [ i ] as j + 1 ; if we reached j = 0 , assign lps [ i ] as 0 as there was no prefix equal to suffix ; return the calculated lps array ; function to count the occurrence of all the prefix in the string s ; call the prefix_function to get lps ; to store the occurrence of all the prefix ; count all the suffixes that are also prefix ; add the occurences of i to smaller prefixes ; adding 1 to all occ [ i ] for all the orignal prefix ; function call to print the occurence of all the prefix ; 
def Print(occ, s):
    for i in range(1, len(s) + 1):
        print(s[0:i], "occur", occ[i], "times.")


def prefix_function(s):
    LPS = [0 for i in range(len(s))]
    for i in range(1, len(s)):
        j = LPS[i - 1]
        while (j > 0 and s[i] != s[j]):
            j = LPS[j - 1]
        if (s[i] == s[j]):
            LPS[i] = j + 1
        else:
            LPS[i] = 0
    return LPS


def count_occurence(s):
    n = len(s)
    LPS = prefix_function(s)
    occ = [0 for i in range(n + 1)]
    for i in range(n):
        occ[LPS[i]] += 1
    for i in range(n - 1, 0, -1):
        occ[LPS[i - 1]] += occ[i]
    for i in range(n + 1):
        occ[i] += 1
    Print(occ, s)


A = "ABACABA"
count_occurence(A)

# Expected output:
A occur 4 times.
AB occur 2 times.
ABA occur 2 times.
ABAC occur 1 times.
ABACA occur 1 times.
ABACAB occur 1 times.
ABACABA occur 1 times.
# maximum sum by picking elements from two arrays in order | set 2 | function to calculate maximum sum ; maximum elements that can be chosen from array a ; maximum elements that can be chosen from array b ; stores the maximum sum possible ; fill the dp [ ] for base case when all elements are selected from a [ ] ; fill the dp [ ] for base case when all elements are selected from b [ ] ; return the final answer ; 
def maximumSum(A, B, length, X, Y):
    l = length
    l1 = min(length, X)
    l2 = min(length, Y)
    dp = [[0 for i in range(l2 + 1)]for i in range(l1 + 1)]
    dp[0][0] = 0
    max_sum = -10 * 9
    for i in range(1, l1 + 1):
        dp[i][0] = dp[i - 1][0] + A[i - 1]
        max_sum = max(max_sum, dp[i][0])
    for i in range(1, l2 + 1):
        dp[0][i] = dp[0][i - 1] + B[i - 1]
        max_sum = max(max_sum, dp[0][i])
    for i in range(1, l1 + 1):
        for j in range(1, l2 + 1):
            if (i + j <= l):
                dp[i][j] = max(dp[i - 1][j] + A[i + j - 1],
                               dp[i][j - 1] + B[i + j - 1])
            max_sum = max(dp[i][j], max_sum)
    return max_sum


if __name__ == '__main__':
    A = [1, 2, 3, 4, 5]
    B = [5, 4, 3, 2, 1]
    X = 3
    Y = 2
    N = len(A)
    print(maximumSum(A, B, N, X, Y))

# Expected output:
21
# min number of operations to reduce n to 0 by subtracting any digits from n | function to reduce an integer n to zero in minimum operations by removing digits from n ; initialise dp [ ] to steps ; iterate for all elements ; for each digit in number i ; either select the number or do not select it ; dp [ n ] will give minimum step for n ; 
def reduceZero(N):
    dp = [1e9 for i in range(N + 1)]
    dp[0] = 0
    for i in range(N + 1):
        for c in str(i):
            dp[i] = min(dp[i], dp[i - (ord(c) - 48)] + 1)
    return dp[N]


N = 25
print(reduceZero(N))

# Expected output:
5
# pentanacci numbers | function to print nth pentanacci number ; initialize first five numbers to base cases ; declare a current variable ; loop to add previous five numbers for each number starting from 5 and then assign first , second , third , fourth to second , third , fourth and curr to fifth respectively ; 
def printpenta(n):
    if (n < 0):
        return
    first = 0
    second = 0
    third = 0
    fourth = 0
    fifth = 1
    curr = 0
    if (n == 0 or n == 1 or n == 2 or n == 3):
        print(first)
    elif (n == 5):
        print(fifth)
    else:
        for i in range(5, n):
            curr = first + second + third + fourth + fifth
            first = second
            second = third
            third = fourth
            fourth = fifth
            fifth = curr
    print(curr)


n = 10
printpenta(n)

# Expected output:
16
# count of binary strings of length n with even set bit count and at most k consecutive 1 s | python3 program for the above approach ; table to store solution of each subproblem ; function to calculate the possible binary strings ; if number of ones is equal to k ; pos : current position base case : when n length is traversed ; sum : count of 1 ' s ▁ ▁ return ▁ the ▁ count ▁ ▁ of ▁ 1' s obtained ; if the subproblem has already been solved ; return the answer ; recursive call when current position is filled with 1 ; recursive call when current position is filled with 0 ; store the solution to this subproblem ; 

import numpy as np
dp = np .ones(((100002, 21, 3)))
dp = -1 * dp


def possibleBinaries(pos, ones, sum, k):
    if (ones == k):
        return 0
    if (pos == 0):
        return 1 if (sum == 0)else 0
    if (dp[pos][ones][sum] != -1):
        return dp[pos][ones][sum]
    ret = (
        possibleBinaries(
            pos -
            1,
            ones +
            1,
            (sum +
             1) %
            2,
            k) +
        possibleBinaries(
            pos -
            1,
            0,
            sum,
            k))
    dp[pos][ones][sum] = ret
    return dp[pos][ones][sum]


N = 3
K = 2
print(int(possibleBinaries(N, 0, 0, K)))

# Expected output:
2
# count of subsequences of length atmost k containing distinct prime elements | python3 program to find the count of distinct prime subsequences at most of of length k from a given array ; initialize all indices as true ; a value in prime [ i ] will finally be false if i is not a prime , else true ; if prime [ p ] is true , then it is a prime ; update all multiples of p as false , i . e . non - prime ; returns number of subsequences of maximum length k and contains distinct primes ; store the primes in the given array ; sort the primes ; store the frequencies of all the distinct primes ; store the frequency of primes ; store the sum of all frequencies ; store the length of subsequence at every instant ; store the frequency ; store the previous count of updated dp ; calculate total subsequences of current of_length ; add the number of subsequences to the answer ; update the value in dp [ i ] ; store the updated dp [ i ] ; 

prime = [True] * 1000000


def SieveOfEratosthenes():
    global prime
    prime[0] = prime[1] = False
    p = 2
    while p * p <= 100000:
        if (prime[p]):
            for i in range(p * p, 100001, p):
                prime[i] = False
        p += 1


def distinctPrimeSubSeq(a, n, k):
    SieveOfEratosthenes()
    primes = []
    for i in range(n):
        if (prime[a[i]]):
            primes .append(a[i])
    l = len(primes)
    primes .sort()
    b = []
    dp = []
    sum = 0
    i = 0
    while i < l:
        count = 1
        x = a[i]
        i += 1
        while (i < l and a[i] == x):
            count += 1
            i += 1
        b .append(count)
        dp .append(count)
        sum += count
    of_length = 2
    leng = len(dp)
    ans = 0
    while (of_length <= k):
        freq = 0
        prev = 0
        for i in range(leng - 1):
            freq += dp[i]
            j = sum - freq
            subseq = b[i] * j
            ans += subseq
            dp[i] = subseq
            prev += dp[i]
        leng -= 1
        sum = prev
        of_length += 1
    ans += (l + 1)
    return ans


if __name__ == "__main__":
    a = [1, 2, 2, 3, 3, 4, 5]
    n = len(a)
    k = 3
    print(distinctPrimeSubSeq(a, n, k))

# Expected output:
18