giulio98/xlcost-single-prompt huggingface dataset:
# count sequences of positive integers having product x | python3 program for the above approach ; function to prthe total number of possible sequences with product x ; precomputation of binomial coefficients ; max length of a subsequence ; ways dp array ; fill i slots using all the primes ; subtract ways for all slots that exactly fill less than i slots ; total possible sequences ; print the resultant count ; 

bin = [[0 for i in range(3000)]for i in range(3000)]


def countWays(arr):
    mod = 10 ** 9 + 7
    bin[0][0] = 1
    for i in range(1, 3000):
        bin[i][0] = 1
        for j in range(1, i + 1):
            bin[i][j] = (bin[i - 1][j] + bin[i - 1][j - 1]) % mod
    n = 0
    for x in arr:
        n += x
    ways = [0] * (n + 1)
    for i in range(1, n + 1):
        ways[i] = 1
        for j in range(len(arr)):
            ways[i] = (ways[i] * bin[arr[j] + i - 1][i - 1]) % mod
        for j in range(1, i):
            ways[i] = ((ways[i] - bin[i][j] * ways[j]) % mod + mod) % mod
    ans = 0
    for x in ways:
        ans = (ans + x) % mod
    print(ans)


if __name__ == '__main__':
    arr = [1, 1]
    countWays(arr)

# Expected output:
3
# maximum subsequence sum obtained by concatenating disjoint subarrays whose lengths are prime | python3 program for the above approach ; function to return all prime numbers smaller than n ; create a boolean array " prime [ 0 . . n ] " ; initialize all its entries as true memset ( seive , true , sizeof ( seive ) ) ; if prime [ p ] is not changed , then it is a prime ; update all multiples of p greater than or equal to the square of it ; stores all prime numbers smaller than max ; store all prime numbers ; if p is prime ; function to build the auxiliary dp array from the start ; base case ; stores all prime numbers < n ; stores prefix sum ; update prefix sum ; iterate over range ; update each state i . e . . when current element is excluded ; find start & end index of subarrays when prime [ i ] is taken ; check if starting point lies in the array ; include the elements al al + 1 . . . ar ; check if element lies before start of selected subarray ; update value of dp [ i ] ; function to find the maximum sum subsequence with prime length ; auxiliary dp array ; build dp array ; print the result ; 

MAX = 100005


def SieveOfEratosthenes():
    seive = [True for i in range(MAX)]
    for p in range(2, MAX):
        if p * p > MAX:
            break
        if (seive[p]):
            for i in range(p * p, MAX, p):
                seive[i] = False
    v = []
    for p in range(2, MAX):
        if (seive[p]):
            v .append(p)
    return v


def build(dp, arr, N):
    dp[0] = 0
    dp[1] = 0
    prime = SieveOfEratosthenes()
    pref = [0 for i in range(N + 1)]
    pref[0] = 0
    for i in range(1, N + 1):
        pref[i] = pref[i - 1] + arr[i - 1]
    for i in range(2, N + 1):
        dp[i] = dp[i - 1]
        for j in range(len(prime) + 1):
            r = i - 1
            l = r - prime[j] + 1
            if (l < 0):
                break
            temp = 0
            temp = pref[r + 1] - pref[l]
            if (l - 2 >= 0):
                temp += dp[l - 2 + 1]
            dp[i] = max(dp[i], temp)


def maxSumSubseq(arr, N):
    dp = [0 for i in range(N + 1)]
    build(dp, arr, N)
    print(dp[N])


if __name__ == '__main__':
    arr = [10, 10, 7, 10, 10, 10]
    N = len(arr)
    maxSumSubseq(arr, N)

# Expected output:
50
# maximum possible score that can be obtained by constructing a binary tree based on given conditions | function to find the maximum score for one possible tree having n nodes n - 1 edges ; number of nodes ; initialize dp [ ] [ ] ; score with 0 vertices is 0 ; traverse the nodes from 1 to n ; find maximum scores for each sum ; iterate over degree of new node ; update the current state ; return maximum score for n node tree having 2 ( n - 1 ) sum of degree ; 
def maxScore(arr):
    N = len(arr)
    N += 1
    dp = [[-100000 for i in range(2 * N)]for i in range(N + 1)]
    dp[0][0] = 0
    for i in range(1, N + 1):
        for s in range(1, 2 * (N - 1) + 1):
            j = 1
            while j <= N - 1 and j <= s:
                dp[i][s] = max(dp[i][s], arr[j - 1] + dp[i - 1][s - j])
                j += 1
    return dp[N][2 * (N - 1)]


if __name__ == '__main__':
    arr = [1, 3, 0]
    print(maxScore(arr))

# Expected output:
8
# minimize cost of choosing and skipping array elements to reach end of the given array | function to find the minimum cost to reach the end of the array from the first element ; store the results ; consider first index cost ; find answer for each position i ; first element ; second element ; for remaining element ; consider min cost for skipping ; last index represents the minimum total cost ; 
def minimumCost(cost, n, x):
    dp = [0] * (n + 2)
    dp[0] = cost[0]
    for i in range(1, n):
        if (i == 1):
            dp[i] = cost[i] + dp[i - 1]
        if (i == 2):
            dp[i] = cost[i] + min(dp[i - 1], x + dp[i - 2])
        if (i >= 3):
            dp[i] = (cost[i] + min(dp[i - 1],
                     min(x + dp[i - 2], 2 * x + dp[i - 3])))
    print(dp[n - 1])


if __name__ == '__main__':
    X = 4
    cost = [6, 3, 9, 2, 1, 3]
    N = len(cost)
    minimumCost(cost, N, X)

# Expected output:
19
# maximum possible sum of non | function to find the maximum sum not exceeding k possible by selecting a subset of non - adjacent elements ; base case ; not selecting current element ; if selecting current element is possible ; return answer ; 
def maxSum(a, n, k):
    if (n <= 0):
        return 0
    option = maxSum(a, n - 1, k)
    if (k >= a[n - 1]):
        option = max(option, a[n - 1] + maxSum(a, n - 2, k - a[n - 1]))
    return option


if __name__ == '__main__':
    arr = [50, 10, 20, 30, 40]
    N = len(arr)
    K = 100
    print(maxSum(arr, N, K))

# Expected output:
90
# count possible binary strings of length n without p consecutive 0 s and q consecutive 1 s | function to check if a satisfy the given condition or not ; stores the length of string ; stores the previous character of the string ; stores the count of consecutive equal characters ; traverse the string ; if current character is equal to the previous character ; if count of consecutive 1 s is more than q ; if count of consecutive 0 s is more than p ; reset value of cnt ; if count of consecutive 1 s is more than q ; if count of consecutive 0 s is more than p ; function to count all distinct binary strings that satisfy the given condition ; stores the length of str ; if length of str is n ; if str satisfy the given condition ; if str does not satisfy the given condition ; append a character '0' at end of str ; append a character '1' at end of str ; return total count of binary strings ; 
def checkStr(str, P, Q):
    N = len(str)
    prev = str[0]
    cnt = 0
    for i in range(N):
        if (str[i] == prev):
            cnt += 1
        else:
            if (prev == '1' and cnt >= Q):
                return False
            if (prev == '0' and cnt >= P):
                return False
            cnt = 1
        prev = str[i]
    if (prev == '1' and cnt >= Q):
        return False
    if (prev == '0' and cnt >= P):
        return False
    return True


def cntBinStr(str, N, P, Q):
    lenn = len(str)
    if (lenn == N):
        if (checkStr(str, P, Q)):
            return 1
        return 0
    X = cntBinStr(str + '0', N, P, Q)
    Y = cntBinStr(str + '1', N, P, Q)
    return X + Y


if __name__ == '__main__':
    N = 5
    P = 2
    Q = 3
    print(cntBinStr("", N, P, Q))

# Expected output:
7
# count possible permutations of given array satisfying the given conditions | function to get the value of binomial coefficient ; stores the value of binomial coefficient ; since c ( n , r ) = c ( n , n - r ) ; calculate the value of c ( n , r ) ; function to get the count of permutations of the array that satisfy the condition ; stores the value of c ( 2 n , n ) ; stores the value of catalan number ; return answer ; 
def binCoff(N, R):
    res = 1
    if (R > (N - R)):
        R = (N - R)
    for i in range(R):
        res *= (N - i)
        res //= (i + 1)
    return res


def cntPermutation(N):
    C_2N_N = binCoff(2 * N, N)
    cntPerm = C_2N_N // (N + 1)
    return cntPerm


if __name__ == '__main__':
    arr = [1, 2, 3, 4]
    N = len(arr)
    print(cntPermutation(N // 2))

# Expected output:
2
# smallest submatrix with kth maximum xor | function to print smallest index of kth maximum xor value of submatrices ; dimensions of matrix ; stores xor values for every index ; min heap to find the kth maximum xor value ; stores indices for corresponding xor values ; traversing matrix to calculate xor values ; insert calculated value in min heap ; if size exceeds k ; remove the minimum ; store smallest index containing xor [ i , j ] ; stores the kth maximum element ; print the required index ; 
def smallestPosition(m, k):
    n = len(m)
    mm = len(m[1])
    xor = [[0 for i in range(mm)]for j in range(n)]
    minHeap = []
    Map = {}
    for i in range(n):
        for j in range(mm):
            if i - 1 >= 0:
                a = xor[i - 1][j]
            else:
                a = 0
            if j - 1 >= 0:
                b = xor[i][j - 1]
            else:
                b = 0
            if i - 1 >= 0 and j - 1 >= 0:
                c = xor[i - 1][j - 1]
            else:
                c = 0
            xor[i][j] = m[i][j] ^ a ^ b ^ c
            minHeap .append(xor[i][j])
            minHeap .sort()
            if (len(minHeap) > k):
                del minHeap[0]
            if xor[i][j]not in Map:
                Map[xor[i][j]] = [i, j]
    minHeap .sort()
    kth_max_e = minHeap[0]
    print((Map[kth_max_e][0] + 1), (Map[kth_max_e][1] + 1))


m = [[1, 2, 3], [2, 2, 1], [2, 4, 2]]
k = 1
smallestPosition(m, k)

# Expected output:
3 2
# length of longest palindrome substring | function to obtain the length of the longest palindromic substring ; length of given string ; stores the maximum length ; iterate over the string ; iterate over the string ; check for palindrome ; if string [ i , j - i + 1 ] is palindromic ; return length of lps ; 
def longestPalSubstr(str):
    n = len(str)
    maxLength = 1
    start = 0
    for i in range(len(str)):
        for j in range(i, len(str), 1):
            flag = 1
            for k in range((j - i + 1) // 2):
                if (str[i + k] != str[j - k]):
                    flag = 0
            if (flag != 0 and (j - i + 1) > maxLength):
                start = i
                maxLength = j - i + 1
    return maxLength


str = "forgeeksskeegfor"
print(longestPalSubstr(str))

# Expected output:
10
# minimum cost to convert m to n by repeated addition of its even divisors | python3 program for the above approach ; function to find the value of minimum steps to convert m to n ; base case ; if n exceeds m ; iterate through all possible even divisors of m ; if m is divisible by i , then find the minimum cost ; add the cost to convert m to m + i and recursively call next state ; return min_cost ; 

inf = 1000000008


def minSteps(m, n):
    if (n == m):
        return 0
    if (m > n):
        return inf
    min_cost = inf
    for i in range(2, m, 2):
        if (m % i == 0):
            min_cost = min(min_cost, m / i + minSteps(m + i, n))
    return min_cost


if __name__ == '__main__':
    M = 6
    N = 24
    minimum_cost = minSteps(M, N)
    if minimum_cost == inf:
        minimum_cost = -1
    print(minimum_cost)

# Expected output:
10.0
# represent a number as the sum of positive numbers ending with 9 | function to find the minimum count of numbers ending with 9 to form n ; extract last digit of n ; calculate the last digit ; if the last digit satisfies the condition ; 
def minCountOfNumbers(N):
    k = N % 10
    z = N - (9 * (9 - k))
    if (z >= 9 and z % 10 == 9):
        return 10 - k
    else:
        return -1


if __name__ == '__main__':
    N = 156
    print(minCountOfNumbers(N))

# Expected output:
4
# binary matrix after flipping submatrices in given range for q queries | function to flip a submatrices ; boundaries of the submatrix ; iterate over the submatrix ; check for 1 or 0 and flip accordingly ; function to perform the queries ; 
def manipulation(matrix, q):
    x1, y1, x2, y2 = q
    for i in range(x1 - 1, x2):
        for j in range(y1 - 1, y2):
            if matrix[i][j]:
                matrix[i][j] = 0
            else:
                matrix[i][j] = 1


def queries_fxn(matrix, queries):
    for q in queries:
        manipulation(matrix, q)


matrix = [[0, 1, 0], [1, 1, 0]]
queries = [[1, 1, 2, 3], [1, 1, 1, 1], [1, 2, 2, 3]]
queries_fxn(matrix, queries)
print(matrix)

# Expected output:
[[0, 1, 0], [0, 1, 0]]
# minimum repeated addition of even divisors of n required to convert n to m | inf is the maximum value which indicates impossible state ; recursive function that considers all possible even divisors of cur ; indicates impossible state ; return 0 if cur == m ; initially it is set to inf that means we can 't transform cur to m ; loop to find even divisors of cur ; if i is divisor of cur ; if i is even ; finding divisors recursively for cur + i ; check another divisor ; find recursively for cur + ( cur / i ) ; return the answer ; function that finds the minimum operation to reduce n to m ; inf indicates impossible state ; 

INF = int(1e7)


def min_op(cur, M):
    if (cur > M):
        return INF
    if (cur == M):
        return 0
    op = int(INF)
    for i in range(2, int(cur ** 1 / 2) + 1):
        if (cur % i == 0):
            if (i % 2 == 0):
                op = min(op, 1 + min_op(cur + i, M))
            if ((cur / i) != i and (cur / i) % 2 == 0):
                op = min(op, 1 + min_op(cur + (cur // i), M))
    return op


def min_operations(N, M):
    op = min_op(N, M)
    if (op >= INF):
        print("-1")
    else:
        print(op)


if __name__ == '__main__':
    N = 6
    M = 24
    min_operations(N, M)

# Expected output:
4
# minimum length of subsequence having unit gcd | function that finds the prime factors of a number ; to store the prime factor ; 2 s that divide n ; n must be odd at this point skip one element ; update the prime factor ; if n is a prime number greater than 2 ; function that finds the shortest subsequence ; check if the prime factor of first number , is also the prime factor of the rest numbers in array ; set corresponding bit of prime factor to 1 , it means both these numbers have the same prime factor ; if no states encountered so far continue for this combination of bits ; update this state with minimum ways to reach this state ; function that print the minimum length of subsequence ; find the prime factors of the first number ; initialize the array with maximum steps , size of the array + 1 for instance ; total number of set bits is equal to the total number of prime factors ; indicates there is one way to reach the number under consideration ; state 0 corresponds to gcd of 1 ; if not found such subsequence then print " - 1" ; else print the length ; 
def findPrimeFactors(n):
    primeFactors = [0 for i in range(9)]
    j = 0
    if (n % 2 == 0):
        primeFactors[j] = 2
        j += 1
        while (n % 2 == 0):
            n >>= 1
    i = 3
    while (i * i <= n):
        if (n % i == 0):
            primeFactors[j] = i
            j += 1
            while (n % i == 0):
                n //= i
        i += 2
    if (n > 2):
        primeFactors[j] = n
        j += 1
    for i in range(0, j + 1):
        primeFactors[i] = 0
    return primeFactors


def findShortestSubsequence(dp, a, index, primeFactors):
    n = len(a)
    for j in range(index, n):
        bitmask = 0
        for p in range(len(primeFactors)):
            if (primeFactors[p] != 0 and a[j] % primeFactors[p] == 0):
                bitmask ^= (1 << p)
        for i in range(len(dp)):
            if (dp[i] == n + 1):
                continue
            dp[bitmask & i] = min(dp[bitmask & i], dp[i] + 1)


def printMinimumLength(a):
    mn = len(a) + 1
    for i in range(len(a) - 1):
        primeFactors = findPrimeFactors(a[i])
        n = len(primeFactors)
        dp = [0 for i in range(1 << n)]
        dp = [len(a) + 1 for i in range(len(dp))]
        setBits = (1 << n) - 1
        dp[setBits] = 1
        findShortestSubsequence(dp, a, i + 1, primeFactors)
        mn = min(dp[0], mn)
    if (mn == len(a) + 1):
        print(-1)
    else:
        print(mn)


if __name__ == '__main__':
    arr = [2, 6, 12, 3]
    printMinimumLength(arr)

# Expected output:
2
# maximum sum of bitwise xor of all elements of two equal length subsets | function that finds the maximum bitwise xor sum of the two subset ; check if the current state is already computed ; initialize answer to minimum value ; iterate through all possible pairs ; check whether ith bit and jth bit of mask is not set then pick the pair ; for all possible pairs find maximum value pick current a [ i ] , a [ j ] and set i , j th bits in mask ; store the maximum value and return the answer ; 
def xorSum(a, n, mask, dp):
    if (dp[mask] != -1):
        return dp[mask]
    max_value = 0
    for i in range(n):
        for j in range(i + 1, n):
            if (i != j and (mask & (1 << i)) == 0 and (mask & (1 << j)) == 0):
                max_value = max(
                    max_value,
                    (a[i] ^ a[j]) +
                    xorSum(
                        a,
                        n,
                        (mask | (
                            1 << i) | (
                            1 << j)),
                        dp))
    dp[mask] = max_value
    return dp[mask]


n = 4
arr = [1, 2, 3, 4]
dp = [-1] * ((1 << n) + 5)
print(xorSum(arr, n, 0, dp))

# Expected output:
10
# count of n | function to find count of n - digit numbers with single digit xor ; range of numbers ; calculate xor of digits ; if xor <= 9 , then increment count ; print the count ; 
def countNums(N):
    l = pow(10, N - 1)
    r = pow(10, N) - 1
    count = 0
    for i in range(l, r + 1):
        xorr = 0
        temp = i
        while (temp > 0):
            xorr = xorr ^ (temp % 10)
            temp //= 10
        if (xorr <= 9):
            count += 1
    print(count)


N = 2
countNums(N)

# Expected output:
66
# maximize length of non | python3 program to implement the above approach ; function to find the maximum length non decreasing subarray by reversing at most one subarray ; dp [ i ] [ j ] be the longest subsequence of a [ 0. . . i ] with first j parts ; maximum length sub - sequence of ( 0. . ) ; maximum length sub - sequence of ( 0. . 1. . ) ; maximum length sub - sequence of ( 0. . 1. .0 . . ) ; maximum length sub - sequence of ( 0. . 1. .0 . .1 . . ) ; find the max length subsequence ; print the answer ; 

import sys


def main(arr, n):
    dp = [[0 for x in range(n)]for y in range(4)]
    if arr[0] == 0:
        dp[0][0] = 1
    else:
        dp[1][0] = 1
    for i in range(1, n):
        if arr[i] == 0:
            dp[0][i] = dp[0][i - 1] + 1
        else:
            dp[0][i] = dp[0][i - 1]
    for i in range(1, n):
        if arr[i] == 1:
            dp[1][i] = max(dp[1][i - 1] + 1, dp[0][i - 1] + 1)
        else:
            dp[1][i] = dp[1][i - 1]
    for i in range(1, n):
        if arr[i] == 0:
            dp[2][i] = max(
                [dp[2][i - 1] + 1, dp[1][i - 1] + 1, dp[0][i - 1] + 1])
        else:
            dp[2][i] = dp[2][i - 1]
    for i in range(1, n):
        if arr[i] == 1:
            dp[3][i] = max([dp[3][i - 1] + 1, dp[2][i - 1] + 1,
                           dp[1][i - 1] + 1, dp[0][i - 1] + 1])
        else:
            dp[3][i] = dp[3][i - 1]
    ans = max([dp[2][n - 1], dp[1][n - 1], dp[0][n - 1], dp[3][n - 1]])
    print(ans)


if __name__ == "__main__":
    n = 4
    arr = [0, 1, 0, 1]
    main(arr, n)

# Expected output:
4
# print the maximum subarray sum | function to print the elements of subarray with maximum sum ; initialize currmax and globalmax with first value of nums ; iterate for all the elemensts of the array ; update currmax ; check if currmax is greater than globalmax ; traverse in left direction to find start index of subarray ; decrement the start index ; printing the elements of subarray with max sum ; 
def SubarrayWithMaxSum(nums):
    currMax = nums[0]
    globalMax = nums[0]
    for i in range(1, len(nums)):
        currMax = max(nums[i], nums[i] + currMax)
        if (currMax > globalMax):
            globalMax = currMax
            endIndex = i
    startIndex = endIndex
    while (startIndex >= 0):
        globalMax -= nums[startIndex]
        if (globalMax == 0):
            break
        startIndex -= 1
    for i in range(startIndex, endIndex + 1):
        print(nums[i], end=" ")


arr = [-2, -5, 6, -2, -3, 1, 5, -6]
SubarrayWithMaxSum(arr)

# Expected output:
6 -2 -3 1 5
# queries to count distinct binary strings of all lengths from n to m satisfying given properties | python3 program to implement the above approach ; function to calculate the count of possible strings ; initialize dp [ 0 ] ; dp [ i ] represents count of strings of length i ; add dp [ i - k ] if i >= k ; update prefix sum array ; 

N = int(1e5 + 5)
MOD = 1000000007
dp = [0] * N


def countStrings(K, Q):
    dp[0] = 1
    for i in range(1, N):
        dp[i] = dp[i - 1]
        if (i >= K):
            dp[i] = (dp[i] + dp[i - K]) % MOD
    for i in range(1, N):
        dp[i] = (dp[i] + dp[i - 1]) % MOD
    for i in range(len(Q)):
        ans = dp[Q[i][1]] - dp[Q[i][0] - 1]
        if (ans < 0):
            ans += MOD
        print(ans)


K = 3
Q = [[1, 4], [3, 7]]
countStrings(K, Q)

# Expected output:
7
24
# minimum possible sum of prices of a triplet from the given array | python3 program to implement the above approach ; function to minimize the sum of price by taking a triplet ; initialize a dp [ ] list ; stores the final result ; iterate for all values till n ; check if num [ j ] > num [ i ] ; update dp [ j ] if it is greater than stored value ; update the minimum sum as ans ; if there is no minimum sum exist then print - 1 else print the ans ; 

import sys


def minSum(n, num, price):
    dp = [0 for i in range(n)]
    for i in range(n):
        dp[i] = sys .maxsize
    ans = sys .maxsize
    for i in range(n):
        for j in range(i + 1, n):
            if (num[j] > num[i]):
                dp[j] = min(dp[j], price[i] + price[j])
                ans = min(ans, dp[i] + price[j])
    if ans is not sys .maxsize:
        return ans
    else:
        return -1


if __name__ == '__main__':
    num = [2, 4, 6, 7, 8]
    price = [10, 20, 100, 20, 40]
    n = len(price)
    print(minSum(n, num, price))

# Expected output:
50
# count of binary strings of length n having equal count of 0 ' s ▁ and ▁ 1' s and count of 1 ' s ▁ â ‰ ¥ ▁ count ▁ of ▁ 0' s in each prefix substring | function to calculate and returns the value of binomial coefficient c ( n , k ) ; since c ( n , k ) = c ( n , n - k ) ; calculate the value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; function to return the count of all binary strings having equal count of 0 ' s ▁ and ▁ 1' s and each prefix substring having frequency of 1 ' s ▁ > = ▁ frequencies ▁ of ▁ 0' s ; if n is odd ; no such strings possible ; otherwise ; calculate value of 2 ncn ; return 2 ncn / ( n + 1 ) ; 
def binomialCoeff(n, k):
    res = 1
    if (k > n - k):
        k = n - k
    for i in range(k):
        res *= (n - i)
        res //= (i + 1)
    return res


def countStrings(N):
    if (N % 2 == 1):
        return 0
    else:
        N //= 2
        c = binomialCoeff(2 * N, N)
        return c // (N + 1)


if __name__ == '__main__':
    N = 6
    print(countStrings(N))

# Expected output:
5