giulio98/xlcost-single-prompt huggingface dataset:
# minimum count of numbers required from given array to represent s | python3 implementation to find the minimum number of sequence required from array such that their sum is equal to given s ; function to find the minimum elements required to get the sum of given value s ; condition if the sequence is found ; condition when no such sequence found ; calling for without choosing the current index value ; calling for after choosing the current index value ; function for every array ; 

import sys


def printAllSubsetsRec(arr, n, v, Sum):
    if (Sum == 0):
        return len(v)
    if (Sum < 0):
        return sys .maxsize
    if (n == 0):
        return sys .maxsize
    x = printAllSubsetsRec(arr, n - 1, v, Sum)
    v .append(arr[n - 1])
    y = printAllSubsetsRec(arr, n, v, Sum - arr[n - 1])
    v .pop(len(v) - 1)
    return min(x, y)


def printAllSubsets(arr, n, Sum):
    v = []
    return printAllSubsetsRec(arr, n, v, Sum)


arr = [2, 1, 4, 3, 5, 6]
Sum = 6
n = len(arr)
print(printAllSubsets(arr, n, Sum))

# Expected output:
1
# minimum count of numbers required from given array to represent s | function to find the count of minimum length of the sequence ; loop to initialize the array as infinite in the row 0 ; loop to find the solution by pre - computation for the sequence ; minimum possible for the previous minimum value of the sequence ; 
def Count(S, m, n):
    table = [[0 for i in range(n + 1)]for i in range(m + 1)]
    for i in range(1, n + 1):
        table[0][i] = 10 ** 9 - 1
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if (S[i - 1] > j):
                table[i][j] = table[i - 1][j]
            else:
                table[i][j] = min(table[i - 1][j], table[i][j - S[i - 1]] + 1)
    return table[m][n]


if __name__ == '__main__':
    arr = [9, 6, 5, 1]
    m = len(arr)
    print(Count(arr, m, 11))

# Expected output:
2
# maximize product of same | python3 implementation to maximize product of same - indexed elements of same size subsequences ; utility function to find the maximum ; utility function to find the maximum scalar product from the equal length sub - sequences taken from the two given array ; return a very small number if index is invalid ; if the sub - problem is already evaluated , then return it ; take the maximum of all the recursive cases ; function to find maximum scalar product from same size sub - sequences taken from the two given array ; initialize a 2 - d array for memoization ; 

INF = 10000000


def maximum(A, B, C, D):
    return max(max(A, B), max(C, D))


def maxProductUtil(X, Y, A, B, dp):
    if (X < 0 or Y < 0):
        return -INF
    if (dp[X][Y] != -1):
        return dp[X][Y]
    dp[X][Y] = maximum(
        A[X] *
        B[Y] +
        maxProductUtil(
            X -
            1,
            Y -
            1,
            A,
            B,
            dp),
        A[X] *
        B[Y],
        maxProductUtil(
            X -
            1,
            Y,
            A,
            B,
            dp),
        maxProductUtil(
            X,
            Y -
            1,
            A,
            B,
            dp))
    return dp[X][Y]


def maxProduct(A, N, B, M):
    dp = [[-1 for i in range(m)]for i in range(n)]
    return maxProductUtil(N - 1, M - 1, A, B, dp)


a = [-2, 6, -2, -5]
b = [-3, 4, -2, 8]
n = len(a)
m = len(b)
print(maxProduct(a, n, b, m))

# Expected output:
54
# check if one string can be converted to other using given operation | function that prints whether is it possible to make a equal to t by performing given operations ; base case , if we put the last character at front of a ; base case , if we put the last character at back of a ; condition if current sequence is matchable ; condition for front move to ( i - 1 ) th character ; condition for back move to ( i - 1 ) th character ; condition if it is possible to make a equal to t ; print final answer ; 
def twoStringsEquality(s, t):
    n = len(s)
    dp = [[0 for i in range(n + 1)]for i in range(n)]
    if (s[n - 1] == t[0]):
        dp[n - 1][1] = 1
    if (s[n - 1] == t[n - 1]):
        dp[n - 1][0] = 1
    for i in range(n - 1, -1, -1):
        for j in range(n - i + 1):
            if (dp[i][j]):
                if (s[i - 1] == t[j]):
                    dp[i - 1][j + 1] = 1
                if (s[i - 1] == t[i + j - 1]):
                    dp[i - 1][j] = 1
    ans = False
    for i in range(n + 1):
        if (dp[0][i] == 1):
            ans = True
            break
    if (ans):
        print("Yes")
    else:
        print("No")


if __name__ == '__main__':
    S = "abab"
    T = "baab"
    twoStringsEquality(S, T)

# Expected output:
Yes
# maximize sum of all elements which are not a part of the longest increasing subsequence | function to find maximum sum ; find total sum of array ; maintain a 2d array ; update the dp array along with sum in the second row ; in case of greater length update the length along with sum ; in case of equal length find length update length with minimum sum ; find the sum that need to be subtracted from total sum ; return the sum ; 
def findSum(arr, n):
    totalSum = 0
    for i in range(n):
        totalSum += arr[i]
    dp = [[0] * n for i in range(2)]
    for i in range(n):
        dp[0][i] = 1
        dp[1][i] = arr[i]
    for i in range(1, n):
        for j in range(i):
            if (arr[i] > arr[j]):
                if (dp[0][i] < dp[0][j] + 1):
                    dp[0][i] = dp[0][j] + 1
                    dp[1][i] = dp[1][j] + arr[i]
                elif (dp[0][i] == dp[0][j] + 1):
                    dp[1][i] = min(dp[1][i], dp[1][j] + arr[i])
    maxm = 0
    subtractSum = 0
    for i in range(n):
        if (dp[0][i] > maxm):
            maxm = dp[0][i]
            subtractSum = dp[1][i]
        elif (dp[0][i] == maxm):
            subtractSum = min(subtractSum, dp[1][i])
    return totalSum - subtractSum


arr = [4, 6, 1, 2, 3, 8]
n = len(arr)
print(findSum(arr, n))

# Expected output:
10
# count of possible permutations of a number represented as a sum of 2 ' s , ▁ 4' s and 6 's only | returns number of ways to reach score n ; table [ i ] will store count of solutions for value i . ; initialize all table values as 0 ; base case ( if given value is 0 , 1 , 2 , or 4 ) ; 
def count(n):
    if (n == 2):
        return 1
    elif (n == 4):
        return 2
    elif (n == 6):
        return 4
    table = [0] * (n + 1)
    for i in range(n + 1):
        table[i] = 0
    table[0] = 0
    table[2] = 1
    table[4] = 2
    table[6] = 4
    for i in range(8, n + 1, 2):
        table[i] = table[i - 2] + table[i - 4] + table[i - 6]
    return table[n]


if __name__ == "__main__":
    n = 8
    print(count(n))

# Expected output:
7
# count of ways to split a given number into prime segments | python3 implementation to count total number of ways to split a string to get prime numbers ; function to check whether a number is a prime number or not ; function to find the count of ways to split string into prime numbers ; 1 based indexing ; consider every suffix up to 6 digits ; number should not have a leading zero and it should be a prime number ; return the final result ; 

MOD = 1000000007


def isPrime(number):
    num = int(number)
    i = 2
    while i * i <= num:
        if ((num % i) == 0):
            return False
        i += 1
    if num > 1:
        return True
    else:
        return False


def countPrimeStrings(number, i):
    if (i == 0):
        return 1
    cnt = 0
    for j in range(1, 7):
        if (i - j >= 0 and number[i - j] != '0' and isPrime(number[i - j:i])):
            cnt += countPrimeStrings(number, i - j)
            cnt %= MOD
    return cnt


if __name__ == "__main__":
    s1 = "3175"
    l = len(s1)
    print(countPrimeStrings(s1, l))

# Expected output:
3
# check if a matrix contains a square submatrix with 0 as boundary element | function checks if square with all 0 's in boundary exists in the matrix ; r1 is the top row , c1 is the left col r2 is the bottom row , c2 is the right ; function checks if the boundary of the square consists of 0 's ; 
def hasSquareOfZeroes(r1, c1, r2, c2):
    global matrix, cache
    if (r1 >= r2 or c1 >= c2):
        return False
    key = (str(r1) + '-' + str(c1) + '-' + str(r2) + '-' + str(c2))
    if (key in cache):
        return cache[key]
    cache[key] = (
        isSquareOfZeroes(
            r1,
            c1,
            r2,
            c2) or hasSquareOfZeroes(
            r1 + 1,
            c1 + 1,
            r2 - 1,
            c2 - 1))
    cache[key] = (
        cache[key] or hasSquareOfZeroes(
            r1,
            c1 + 1,
            r2 - 1,
            c2) or hasSquareOfZeroes(
            r1 + 1,
            c1,
            r2,
            c2 - 1))
    cache[key] = (
        cache[key] or hasSquareOfZeroes(
            r1 + 1,
            c1 + 1,
            r2,
            c2) or hasSquareOfZeroes(
            r1,
            c1,
            r2 - 1,
            c2 - 1))
    return cache[key]


def isSquareOfZeroes(r1, c1, r2, c2):
    global matrix
    for row in range(r1, r2 + 1):
        if (matrix[row][c1] != 0 or matrix[row][c2] != 0):
            return False
    for col in range(c1, c2 + 1):
        if (matrix[r1][col] != 0 or matrix[r2][col] != 0):
            return False
    return True


def squareOfZeroes():
    global matrix, cache
    lastIdx = len(matrix) - 1
    return hasSquareOfZeroes(0, 0, lastIdx, lastIdx)


if __name__ == '__main__':
    cache = {}
    matrix = [[1, 1, 1, 0, 1, 0], [0, 0, 0, 0, 0, 1], [0, 1, 1, 1, 0, 1], [
        0, 0, 0, 1, 0, 1], [0, 1, 1, 1, 0, 1], [0, 0, 0, 0, 0, 1]]
    ans = squareOfZeroes()
    if (ans == 1):
        print("True")
    else:
        print("False")

# Expected output:
True
# number of ways to obtain each numbers in range [ 1 , b + c ] by adding any two numbers in range [ a , b ] and [ b , c ] | python3 program to calculate the number of ways ; initialising the array with zeros . you can do using memset too . ; printing the array ; 
def CountWays(a, b, c):
    x = b + c + 1
    arr = [0] * x
    for i in range(a, b + 1):
        for j in range(b, c + 1):
            arr[i + j] += 1
    for i in range(1, x):
        print(arr[i], end=" ")


if __name__ == '__main__':
    a = 1
    b = 2
    c = 2
    CountWays(a, b, c)

# Expected output:
0 0 1 1
# number of ways to obtain each numbers in range [ 1 , b + c ] by adding any two numbers in range [ a , b ] and [ b , c ] | python3 program to calculate the number of ways ; 2 is added because sometimes we will decrease the value out of bounds . ; initialising the array with zeros . ; printing the array ; 
def CountWays(a, b, c):
    x = b + c + 2
    arr = [0] * x
    for i in range(1, b + 1):
        arr[i + b] = arr[i + b] + 1
        arr[i + c + 1] = arr[i + c + 1] - 1
    for i in range(1, x - 1):
        arr[i] += arr[i - 1]
        print(arr[i], end=" ")


if __name__ == '__main__':
    a = 1
    b = 2
    c = 2
    CountWays(a, b, c)

# Expected output:
0 0 1 1
# count of distinct possible strings after performing given operations | function that prints the number of different strings that can be formed ; computing the length of the given string ; base case ; traverse the given string ; if two consecutive 1 ' s ▁ ▁ or ▁ 2' s are present ; otherwise take the previous value ; 
def differentStrings(s):
    n = len(s)
    dp = [0] * (n + 1)
    dp[0] = dp[1] = 1
    for i in range(1, n):
        if (s[i] == s[i - 1] and (s[i] == '1' or s[i] == '2')):
            dp[i + 1] = dp[i] + dp[i - 1]
        else:
            dp[i + 1] = dp[i]
    print(dp[n])


if __name__ == "__main__":
    S = "0111022110"
    differentStrings(S)

# Expected output:
12
# sum of cost of all paths to reach a given cell in a matrix | python3 implementation to find the sum of cost of all paths to reach ( m , n ) ; function for computing combination ; function to find the factorial of n ; loop to find the factorial of a given number ; function for coumputing the sum of all path cost ; loop to find the contribution of each ( i , j ) in the all possible ways ; count number of times ( i , j ) visited ; add the contribution of grid [ i ] [ j ] in the result ; 

Col = 3


def nCr(n, r):
    return fact(n) / (fact(r) * fact(n - r))


def fact(n):
    res = 1
    for i in range(2, n + 1):
        res = res * i
    return res


def sumPathCost(grid, m, n):
    sum = 0
    count = 0
    for i in range(0, m + 1):
        for j in range(0, n + 1):
            count = (nCr(i + j, i) * nCr(m + n - i - j, m - i))
            sum += count * grid[i][j]
    return sum


if __name__ == '__main__':
    m = 2
    n = 2
    grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    print(int(sumPathCost(grid, m, n)))

# Expected output:
150
# count numbers in a range with digit sum divisible by k having first and last digit different | python3 program to count numbers in a range with digit sum divisible by k having first and last digit different ; for calculating the upper bound of the sequence . ; checking whether the sum of digits = 0 or not and the corner case as number equal to 1 ; if the state is visited then return the answer of this state directly . ; for checking whether digit to be placed is up to upper bound at the position pos or upto 9 ; calculating new digit sum modulo k ; check if there is a prefix of 0 s and current digit != 0 ; then current digit will be the starting digit ; update the boolean flag that the starting digit has been found ; at n - 1 , check if current digit and starting digit are the same then no need to calculate this answer ; else find the answer ; function to find the required count ; setting up the upper bound ; calculating f ( r ) ; setting up the upper bound ; calculating f ( l - 1 ) ; 

K = 0
N = 0
v = []
dp = [[[[[-1 for i in range(2)]for j in range(2)]for k in range(10)]
       for l in range(1000)]for m in range(20)]


def init(x):
    global K
    global N
    global v
    v = []
    while (x > 0):
        v .append(x % 10)
        x //= 10
    v = v[::-1]
    N = len(v)


def fun(pos, sum, st, check, f):
    global N
    global v
    if (pos == N):
        return (sum == 0 and check == 1)
    if (dp[pos][sum][st][check][f] != -1):
        return dp[pos][sum][st][check][f]
    lmt = 9
    if (f == False):
        lmt = v[pos]
    ans = 0
    for digit in range(lmt + 1):
        nf = f
        new_sum = (sum + digit) % K
        new_check = check
        new_st = st
        if (f == 0 and digit < lmt):
            nf = 1
        if (check == 0 and digit != 0):
            new_st = digit
            new_check = 1
        if (pos == N - 1 and new_st == digit):
            continue
        ans += fun(pos + 1, new_sum, new_st, new_check, nf)
        dp[pos][sum][st][check][f] = ans
    return ans


def findCount(L, R, K):
    init(R)
    r_ans = fun(0, 0, 0, 0, 0)
    init(L - 1)
    r_ans = 0
    l_ans = fun(0, 0, 0, 0, 0)
    print(l_ans - r_ans)


if __name__ == '__main__':
    L = 10
    R = 20
    K = 2
    findCount(L, R, K)

# Expected output:
5
# split a binary string into k subsets minimizing sum of products of occurrences of 0 and 1 | python3 program to split a given string into k segments such that the sum of product of occurence of characters in them is minimized ; function to return the minimum sum of products of occurences of 0 and 1 in each segments ; store the length of the string ; not possible to generate subsets greater than the length of string ; if the number of subsets equals the length ; precompute the sum of products for all index ; calculate the minimum sum of products for k subsets ; 

import sys


def minSumProd(S, K):
    Len = len(S)
    if (K > Len):
        return -1
    if (K == Len):
        return 0
    dp = [0] * Len
    count_zero = 0
    count_one = 0
    for j in range(0, Len, 1):
        if (S[j] == '0'):
            count_zero += 1
        else:
            count_one += 1
        dp[j] = count_zero * count_one
    for i in range(1, K):
        for j in range(Len - 1, i - 1, -1):
            count_zero = 0
            count_one = 0
            dp[j] = sys .maxsize
            for k in range(j, i - 1, -1):
                if (S[k] == '0'):
                    count_zero += 1
                else:
                    count_one += 1
                dp[j] = min(dp[j], count_zero * count_one + dp[k - 1])
    return dp[Len - 1]


if __name__ == '__main__':
    S = "1011000110110100"
    K = 5
    print(minSumProd(S, K))

# Expected output:
8
# minimize prize count required such that smaller value gets less prize in an adjacent pair | function to find the minimum number of required such that adjacent smaller elements gets less number of prizes ; loop to compute the smaller elements at the left ; loop to find the smaller elements at the right ; loop to find the minimum prizes required ; 
def minPrizes(arr, n):
    dpLeft = [0] * n
    dpLeft[0] = 1
    for i in range(n):
        if arr[i] > arr[i - 1]:
            dpLeft[i] = dpLeft[i - 1] + 1
        else:
            dpLeft[i] = 1
    dpRight = [0] * n
    dpRight[-1] = 1
    for i in range(n - 2, -1, -1):
        if arr[i] > arr[i + 1]:
            dpRight[i] = dpRight[i + 1] + 1
        else:
            dpRight[i] = 1
    totalPrizes = 0
    for i in range(n):
        totalPrizes += max(dpLeft[i], dpRight[i])
    print(totalPrizes)


arr = [1, 2, 2, 3]
n = len(arr)
minPrizes(arr, n)

# Expected output:
6
# maximum sum subsequence with values differing by at least 2 | python3 program to find maximum sum subsequence with values differing by at least 2 ; function to find maximum sum subsequence such that two adjacent values elements are not selected ; map to store the frequency of array elements ; make a dp array to store answer upto i th value ; base cases ; iterate for all possible values of arr [ i ] ; return the last value ; 

from collections import defaultdict


def get_max_sum(arr, n):
    freq = defaultdict(lambda: 0)
    for i in range(n):
        freq[arr[i]] += 1
    dp = [0] * 100001
    dp[0] = 0
    dp[1] = freq[0]
    for i in range(2, 100000 + 1):
        dp[i] = max(dp[i - 1], dp[i - 2] + i * freq[i])
    return dp[100000]


N = 3
arr = [2, 2, 3]
print(get_max_sum(arr, N))

# Expected output:
4
# minimum flips required to keep all 1 s together in a binary string | python implementation for minimum number of flips required in a binary string such that all the 1 atms are together ; length of the binary string ; initial state of the dp dp [ 0 ] [ 0 ] will be 1 if the current bit is 1 and we have to flip it ; initial state of the dp dp [ 0 ] [ 1 ] will be 1 if the current bit is 0 and we have to flip it ; dp [ i ] [ 0 ] = flips required to make all previous bits zero + flip required to make current bit zero ; dp [ i ] [ 1 ] = minimum flips required to make all previous states 0 or make previous states 1 satisfying the condition ; minimum of answer and flips required to make all bits 0 ; 
def minFlip(a):
    n = len(a)
    dp = [[0, 0]for i in range(n)]
    dp[0][0] = int(a[0] == '1')
    dp[0][1] = int(a[0] == '0')
    for i in range(1, n):
        dp[i][0] = dp[i - 1][0] + int(a[i] == '1')
        dp[i][1] = min(dp[i - 1]) + int(a[i] == '0')
    answer = 10 ** 18
    for i in range(n):
        answer = min(answer, dp[i][1] + dp[n - 1][0] - dp[i][0])
    return min(answer, dp[n - 1][0])


s = "1100111000101"
print(minFlip(s))

# Expected output:
4
# length of longest increasing index dividing subsequence | function to find the length of the longest increasing sub - sequence such that the index of the element is divisible by index of previous element ; initialize the dp [ ] array with 1 as a single element will be of 1 length ; traverse the given array ; if the index is divisible by the previous index ; if increasing subsequence identified ; longest length is stored ; 
def LIIDS(arr, N):
    dp = []
    for i in range(1, N + 1):
        dp .append(1)
    ans = 0
    for i in range(1, N + 1):
        j = i + i
        while j <= N:
            if j < N and i < N and arr[j] > arr[i]:
                dp[j] = max(dp[j], dp[i] + 1)
            j += i
        if i < N:
            ans = max(ans, dp[i])
    return ans


arr = [1, 2, 3, 7, 9, 10]
N = len(arr)
print(LIIDS(arr, N))

# Expected output:
3
# count of subarrays having exactly k perfect square numbers | python3 program to count of subarrays having exactly k perfect square numbers . ; a utility function to check if the number n is perfect square or not ; find floating point value of square root of x . ; if square root is an integer ; function to find number of subarrays with sum exactly equal to k ; stl map to store number of subarrays starting from index zero having particular value of sum . ; to store the sum of element traverse so far ; add current element to currsum ; if currsum = k , then a new subarray is found ; if currsum > k then find the no . of subarrays with sum currsum - k and exclude those subarrays ; add currsum to count of different values of sum ; return the final result ; function to count the subarray with k perfect square numbers ; update the array element ; if current element is perfect square then update the arr [ i ] to 1 ; else change arr [ i ] to 0 ; function call ; 

from collections import defaultdict
import math


def isPerfectSquare(x):
    sr = math .sqrt(x)
    return ((sr - math .floor(sr)) == 0)


def findSubarraySum(arr, n, K):
    prevSum = defaultdict(int)
    res = 0
    currsum = 0
    for i in range(n):
        currsum += arr[i]
        if (currsum == K):
            res += 1
        if ((currsum - K) in prevSum):
            res += (prevSum[currsum - K])
        prevSum[currsum] += 1
    return res


def countSubarray(arr, n, K):
    for i in range(n):
        if (isPerfectSquare(arr[i])):
            arr[i] = 1
        else:
            arr[i] = 0
    print(findSubarraySum(arr, n, K))


if __name__ == "__main__":
    arr = [2, 4, 9, 2]
    K = 2
    N = len(arr)
    countSubarray(arr, N, K)

# Expected output:
4
# number of ways to split n as sum of k numbers from the given range | python3 implementation to count the number of ways to divide n in k groups such that each group has elements in range [ l , r ] ; function to count the number of ways to divide the number n in k groups such that each group has number of elements in range [ l , r ] ; base case ; if n is divides completely into less than k groups ; put all possible values greater equal to prev ; function to count the number of ways to divide the number n ; 

mod = 1000000007


def calculate(pos, left, k, L, R):
    if (pos == k):
        if (left == 0):
            return 1
        else:
            return 0
    if (left == 0):
        return 0
    answer = 0
    for i in range(L, R + 1):
        if (i > left):
            break
        answer = (answer + calculate(pos + 1, left - i, k, L, R)) % mod
    return answer


def countWaystoDivide(n, k, L, R):
    return calculate(0, n, k, L, R)


N = 12
K = 3
L = 1
R = 5
print(countWaystoDivide(N, K, L, R))

# Expected output:
10
# check if it is possible to get given sum by taking one element from each row | function that prints whether is it possible to make sum equal to k ; base case ; condition if we can make sum equal to current column by using above rows ; iterate through current column and check whether we can make sum less than or equal to k ; printing whether is it possible or not ; 
def PossibleSum(n, m, v, k):
    dp = [[0] * (k + 1)for i in range(n + 1)]
    dp[0][0] = 1
    for i in range(n):
        for j in range(k + 1):
            if dp[i][j] == 1:
                for d in range(m):
                    if (j + v[i][d]) <= k:
                        dp[i + 1][j + v[i][d]] = 1
    if dp[n][k] == 1:
        print("YES")
    else:
        print("NO")


N = 2
M = 10
K = 5
arr = [[4, 0, 15, 3, 2, 20, 10, 1, 5, 4], [4, 0, 10, 3, 2, 25, 4, 1, 5, 4]]
PossibleSum(N, M, arr, K)

# Expected output:
YES