giulio98/xlcost-single-prompt huggingface dataset:
# modify array by merging elements with addition such that it consists of only primes . | dp array to store the ans for max 20 elements ; to check whether the number is prime or not ; function to check whether the array can be modify so that there are only primes ; if curr is prime and all elements are visited , return true ; if all elements are not visited , set curr = 0 , to search for new prime sum ; if all elements are visited ; if the current sum is not prime return false ; if this state is already calculated , return the answer directly ; try all state of mask ; if ith index is not set ; add the current element and set ith index and recur ; if subset can be formed then return true ; after every possibility of mask , if the subset is not formed , return false by memoizing . ; 

dp = [0] * (1 << 20)


def isprime(n):

    if (n == 1):
        return False
    for i in range(2, n + 1):
        if (n % i == 0):
            return False

    return True


def solve(arr, curr, mask, n):
    if (isprime(curr)):
        if (mask == (1 << n) - 1):
            return True
        curr = 0
    if (mask == (1 << n) - 1):
        if (isprime(curr) == False):
            return False
    if (dp[mask] != False):
        return dp[mask]
    for i in range(n):
        if ((mask & 1 << i) == False):
            if (solve(arr, curr + arr[i],
                      mask | 1 << i, n)):
                return True
    return (dp[mask] == False)


arr = [3, 6, 7, 13]
n = len(arr)
if (solve(arr, 0, 0, n)):
    print("YES")
else:
    print("NO")

# Expected output:
YES
# maximum sum in circular array such that no two elements are adjacent | set 2 | store the maximum possible at each index ; when i exceeds the index of the last element simply return 0 ; if the value has already been calculated , directly return it from the dp array ; the next states are don 't take  this element and go to (i + 1)th state  else take this element  and go to (i + 2)th state ; function to find the max value ; subarr contains elements from 0 to arr . size ( ) - 2 ; initializing all the values with - 1 ; calculating maximum possible sum for first case ; subarr contains elements from 1 to arr . size ( ) - 1 ; re - initializing all values with - 1 ; calculating maximum possible sum for second case ; printing the maximum between them ; 

dp = []


def maxSum(i, subarr):
    if (i >= len(subarr)):
        return 0
    if (dp[i] != -1):
        return dp[i]
    dp[i] = max(maxSum(i + 1, subarr), subarr[i] + maxSum(i + 2, subarr))
    return dp[i]


def Func(arr):
    subarr = arr
    subarr .pop()
    global dp
    dp = [-1] * (len(subarr))
    max1 = maxSum(0, subarr)
    subarr = arr
    subarr = subarr[:]
    del dp
    dp = [-1] * (len(subarr))
    max2 = maxSum(0, subarr)
    print(max(max1, max2))


if __name__ == "__main__":
    arr = [1, 2, 3, 1]
    Func(arr)

# Expected output:
4
# count all square sub | python3 program to count total number of k x k sub matrix whose sum is greater than the given number s ; function to create prefix sum matrix from the given matrix ; store first value in table ; initialize first row of matrix ; initialize first column of matrix ; initialize rest table with sum ; utility function to count the submatrix whose sum is greater than the s ; loop to iterate over all the possible positions of the given matrix mat [ ] [ ] ; condition to check , if k x k is first sub matrix ; condition to check sub - matrix has no margin at top ; condition when sub matrix has no margin at left ; condition when submatrix has margin at top and left ; increment count , if sub matrix sum is greater than s ; function to count submatrix of size k x k such that sum if greater than or equal to s ; for loop to initialize prefix sum matrix with zero , initially ; function to create the prefix sum matrix ; 

dim = 5


def createTable(mtrx, k, p, dp):
    dp[0][0] = mtrx[0][0]
    for j in range(1, dim):
        dp[0][j] = mtrx[0][j] + dp[0][j - 1]
    for i in range(1, dim):
        dp[i][0] = mtrx[i][0] + dp[i - 1][0]
    for i in range(1, dim):
        for j in range(1, dim):
            dp[i][j] = (mtrx[i][j] + dp[i - 1][j] +
                        dp[i][j - 1] - dp[i - 1][j - 1])


def countSubMatrixUtil(dp, k, p):
    count = 0
    subMatSum = 0
    for i in range(k - 1, dim):
        for j in range(k - 1, dim, 1):
            if (i == (k - 1) or j == (k - 1)):
                if (i == (k - 1) and j == (k - 1)):
                    subMatSum = dp[i][j]
                elif (i == (k - 1)):
                    subMatSum = dp[i][j] - dp[i][j - k]
                else:
                    subMatSum = dp[i][j] - dp[i - k][j]
            else:
                subMatSum = (dp[i][j] - dp[i - k][j] - dp[i]
                             [j - k] + dp[i - k][j - k])
            if (subMatSum >= p):
                count += 1
    return count


def countSubMatrix(mtrx, k, p):
    dp = [[0 for i in range(dim)]for j in range(dim)]
    for i in range(dim):
        for j in range(dim):
            dp[i][j] = 0
    createTable(mtrx, k, p, dp)
    return countSubMatrixUtil(dp, k, p)


if __name__ == '__main__':
    mtrx = [[1, 7, 1, 1, 1], [2, 2, 2, 2, 2], [
        3, 9, 6, 7, 3], [4, 3, 2, 4, 5], [5, 1, 5, 3, 1]]
    k = 3
    p = 35
    print(countSubMatrix(mtrx, k, p))

# Expected output:
5
# maximize product of digit sum of consecutive pairs in a subsequence of length k | python3 implementation to find the maximum product of the digit sum of the consecutive pairs of the subsequence of the length k ; function to find the product of two numbers digit sum in the pair ; loop to find the digits of the number ; loop to find the digits of other number ; function to find the subsequence of the length k ; base case ; condition when we didn 't reach  the length k, but ran out of  elements of the array ; condition if already calculated ; if length upto this point is odd ; if length is odd , it means we need second element of this current pair , calculate the product of digit sum of current and previous element and recur by moving towards next index ; if length upto this point is even ; exclude this current element and recur for next elements . ; return by memoizing it , by selecting the maximum among two choices . ; 

import sys
MAX = 100
dp = []
for i in range(1000):
    temp1 = []
    for j in range(MAX):
        temp2 = []
        for k in range(MAX):
            temp2 .append(0)
        temp1 .append(temp2)
    dp .append(temp1)


def productDigitSum(x, y):
    sumx = 0
    while x:
        sumx += x % 10
        x = x // 10
    sumy = 0
    while y:
        sumy += y % 10
        y = y // 10
    return sumx * sumy


def solve(arr, i, len, prev, n, k):
    if len == k:
        return 0
    if i == n:
        return -sys .maxsize - 1
    if dp[i][len][prev]:
        return dp[i][len][prev]
    if len & 1:
        inc = (
            productDigitSum(
                arr[prev],
                arr[i]) +
            solve(
                arr,
                i +
                1,
                len +
                1,
                i,
                n,
                k))
    else:
        inc = solve(arr, i + 1, len + 1, i, n, k)
    exc = solve(arr, i + 1, len, prev, n, k)
    dp[i][len][prev] = max(inc, exc)
    return dp[i][len][prev]


arr = [10, 5, 9, 101, 24, 2, 20, 14]
n = len(arr)
k = 6
print(solve(arr, 0, 0, 0, n, k))

# Expected output:
69
# maximum of all distances to the nearest 1 cell from any 0 cell in a binary matrix | python3 program to find the maximum distance from a 0 - cell to a 1 - cell ; if the matrix consists of only 0 ' s ▁ ▁ or ▁ only ▁ 1' s ; if it 's a 0-cell ; calculate its distance with every 1 - cell ; compare and store the minimum ; compare ans store the maximum ; 
def maxDistance(grid):

    one = []
    M = len(grid)
    N = len(grid[0])
    ans = -1

    for i in range(M):
        for j in range(N):
            if (grid[i][j] == 1):
                one.append([i, j])
    if (one == [] or M * N == len(one)):
        return -1

    for i in range(M):
        for j in range(N):
            if (grid[i][j] == 1):
                continue
            dist = float('inf')

            for p in one:
                d = abs(p[0] - i) + abs(p[1] - j)
                dist = min(dist, d)

                if (dist <= ans):
                    break
                ans = max(ans, dist)

    return ans


arr = [[0, 0, 1], [0, 0, 0], [0, 0, 0]]
print(maxDistance(arr))

# Expected output:
4
# maximum of all distances to the nearest 1 cell from any 0 cell in a binary matrix | function to find the maximum distance ; queue to store all 1 - cells ; grid dimensions ; directions traversable from a given a particular cell ; if the grid contains only 0 s or only 1 s ; access every 1 - cell ; traverse all possible directions from the cells ; check if the cell is within the boundaries or contains a 1 ; 
def maxDistance(grid):
    q = []
    M = len(grid)
    N = len(grid[0])
    ans = -1
    dirs = [[0, 1], [1, 0], [0, -1], [-1, 0]]
    for i in range(M):
        for j in range(N):
            if (grid[i][j] == 1):
                q .append([i, j])
    if (len(q) == 0 or M * N == len(q)):
        return -1
    while (len(q) > 0):
        cnt = len(q)
        while (cnt > 0):
            p = q[0]
            q .pop()
            for Dir in dirs:
                x = p[0] + Dir[0]
                y = p[1] + Dir[1]
                if (x < 0 or x >= M or y < 0 or y >= N or grid[x][y]):
                    continue
                q .append([x, y])
                grid[x][y] = 1
            cnt -= 1
        ans += 2
    return ans


arr = [[0, 0, 1], [0, 0, 0], [0, 0, 1]]
print(maxDistance(arr))

# Expected output:
3
# count the number of ways to give ranks for n students such that same ranks are possible | python3 program to calculate the number of ways to give ranks for n students such that same ranks are possible ; initializing a table in order to store the bell triangle ; function to calculate the k - th bell number ; if we have already calculated the bell numbers until the required n ; base case ; first bell number ; if the value of the bell triangle has already been calculated ; fill the defined dp table ; function to return the number of ways to give ranks for n students such that same ranks are possible ; resizing the dp table for the given value of n ; variables to store the answer and the factorial value ; iterating till n ; simultaneously calculate the k ! ; computing the k - th bell number and multiplying it with k ! ; 

mod = 1e9 + 7
dp = [[-1 for x in range(6)]for y in range(6)]


def f(n, k):
    if (n < k):
        return 0
    if (n == k):
        return 1
    if (k == 1):
        return 1
    if (dp[n][k] != -1):
        return dp[n][k]
    dp[n][k] = ((((k * f(n - 1, k)) % mod + (f(n - 1, k - 1)) % mod) % mod))
    return dp[n][k]


def operation(n):
    global dp
    ans = 0
    fac = 1
    for k in range(1, n + 1):
        fac *= k
        ans = (ans + (fac * f(n, k)) % mod) % mod
    return ans


if __name__ == "__main__":
    n = 5
    print(int(operation(n)))

# Expected output:
541
# print all longest dividing subsequence in an array | function to print lds [ i ] element ; traverse the max [ ] ; function to construct and print longest dividing subsequence ; 2d vector for storing sequences ; push the first element to lds [ ] [ ] ; interate over all element ; loop for every index till i ; if current elements divides arr [ i ] and length is greater than the previous index , then insert the current element to the sequences lds [ i ] ; l [ i ] ends with arr [ i ] ; lds stores the sequences till each element of arr [ ] traverse the lds [ ] [ ] to find the maximum length ; print all lds with maximum length ; find size ; if size = maxlength ; print lds ; 
def printLDS(Max):
    for it in Max:
        print(it, end=" ")


def LongestDividingSeq(arr, N):
    LDS = [[]for i in range(N)]
    LDS[0].append(arr[0])
    for i in range(1, N):
        for j in range(i):
            if ((arr[i] % arr[j] == 0) and (len(LDS[i]) < len(LDS[j]) + 1)):
                LDS[i] = LDS[j].copy()
        LDS[i].append(arr[i])
    maxLength = 0
    for i in range(N):
        x = len(LDS[i])
        maxLength = max(maxLength, x)
    for i in range(N):
        size = len(LDS[i])
        if (size == maxLength):
            printLDS(LDS[i])
            print()


arr = [2, 11, 16, 12, 36, 60, 71]
N = len(arr)
LongestDividingSeq(arr, N)

# Expected output:
2 12 36 
2 12 60
# count the number of ordered sets not containing consecutive numbers | function to calculate the count of ordered set for a given size ; base cases ; function returns the count of all ordered sets ; prestore the factorial value ; iterate all ordered set sizes and find the count for each one maximum ordered set size will be smaller than n as all elements are distinct and non consecutive ; multiply ny size ! for all the arrangements because sets are ordered ; add to total answer ; 
def CountSets(x, pos):
    if (x <= 0):
        if (pos == 0):
            return 1
        else:
            return 0
    if (pos == 0):
        return 1
    answer = (CountSets(x - 1, pos) + CountSets(x - 2, pos - 1))
    return answer


def CountOrderedSets(n):
    factorial = [1 for i in range(10000)]
    factorial[0] = 1
    for i in range(1, 10000, 1):
        factorial[i] = factorial[i - 1] * i
    answer = 0
    for i in range(1, n + 1, 1):
        sets = CountSets(n, i) * factorial[i]
        answer = answer + sets
    return answer


if __name__ == '__main__':
    N = 3
    print(CountOrderedSets(N))

# Expected output:
5
# maximum sum such that exactly half of the elements are selected and no two adjacent | python3 program to find maximum sum possible such that exactly floor ( n / 2 ) elements are selected and no two selected elements are adjacent to each other ; function return the maximum sum possible under given condition ; intitialising the dp table ; base case ; condition to select the current element ; condition to not select the current element if possible ; 

import sys


def MaximumSum(a, n):
    dp = [[0 for i in range(n + 1)]for j in range(n + 1)]
    for i in range(n + 1):
        for j in range(n + 1):
            dp[i][j] = -sys .maxsize - 1
    for i in range(n + 1):
        dp[i][0] = 0
    for i in range(1, n + 1, 1):
        for j in range(1, i + 1, 1):
            val = -sys .maxsize - 1
            if ((i - 2 >= 0 and dp[i - 2][j - 1]
                    != -sys .maxsize - 1) or i - 2 < 0):
                if (i - 2 >= 0):
                    val = a[i - 1] + dp[i - 2][j - 1]
                else:
                    val = a[i - 1]
            if (i - 1 >= j):
                val = max(val, dp[i - 1][j])
            dp[i][j] = val
    return dp[n][n // 2]


if __name__ == '__main__':
    A = [1, 2, 3, 4, 5, 6]
    N = len(A)
    print(MaximumSum(A, N))

# Expected output:
12
# check if n can be converted to the form k power k by the given operation | python3 implementation to check whether a given number n can be converted to the form k power k by the given operation ; function to check if n can be converted to k power k ; check if n is of the form k ^ k ; iterate through each digit of n ; check if it is possible to obtain number of given form ; reduce the number each time ; return the result ; function to check the above method ; check if conversion if possible ; 

kPowKform = dict()


def func(n):
    global kPowKform
    if (n <= 0):
        return 0
    if (n in kPowKform):
        return 1
    answer = 0
    x = n
    while (x > 0):
        d = x % 10
        if (d != 0):
            if (func(n - d * d)):
                answer = 1
                break
        x //= 10
    return answer


def canBeConverted(n):
    if (func(n)):
        print("Yes")
    else:
        print("No")


if __name__ == '__main__':
    N = 90
    for i in range(1, 9):
        val = 1
        for j in range(1, i + 1):
            val *= i
        kPowKform[val] = 1
    canBeConverted(N)

# Expected output:
No
# count of subarrays of an array having all unique digits | function to check whether the subarray has all unique digits ; storing all digits occurred ; traversing all the numbers of v ; storing all digits of v [ i ] ; checking whether digits of v [ i ] have already occurred ; inserting digits of v [ i ] in the set ; function to count the number subarray with all digits unique ; traverse through all the subarrays ; to store elements of this subarray ; generate all subarray and store it in vector ; check whether this subarray has all digits unique ; increase the count ; return the count ; 
def check(v):
    digits = set()
    for i in range(len(v)):
        d = set()
        while (v[i] != 0):
            d .add(v[i] % 10)
            v[i] //= 10
        for it in d:
            if it in digits:
                return False
        for it in d:
            digits .add(it)
    return True


def numberOfSubarrays(a, n):
    answer = 0
    for i in range(1, 1 << n):
        temp = []
        for j in range(n):
            if (i & (1 << j)):
                temp .append(a[j])
        if (check(temp)):
            answer += 1
    return answer


if __name__ == "__main__":
    N = 4
    A = [1, 12, 23, 34]
    print(numberOfSubarrays(A, N))

# Expected output:
7
# smallest n digit number whose sum of square of digits is a perfect square | python3 implementation to find smallest n digit number whose sum of square of digits is a perfect square ; function to check if number is a perfect square ; function to calculate the smallest n digit number ; place digits greater than equal to prev ; check if placing this digit leads to a solution then return it ; else backtrack ; create a representing the n digit number ; 

from math import sqrt


def isSquare(n):
    k = int(sqrt(n))
    return (k * k == n)


def calculate(pos, prev, sum, v):
    if (pos == len(v)):
        return isSquare(sum)
    for i in range(prev, 9 + 1):
        v[pos] = i
        sum += i * i
        if (calculate(pos + 1, i, sum, v)):
            return 1
        sum -= i * i
    return 0


def minValue(n):
    v = [0] * (n)
    if (calculate(0, 1, 0, v)):
        answer = ""
        for i in range(len(v)):
            answer += chr(v[i] + ord('0'))
        return answer
    else:
        return "-1"


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

# Expected output:
34
# sum of gcd of all possible sequences | pyhton3 implementation of the above approach ; a recursive function that generates all the sequence and find gcd ; if we reach the sequence of length n g is the gcd of the sequence ; initialise answer to 0 ; placing all possible values at this position and recursively find the gcd of the sequence ; take gcd of gcd calculated uptill now i . e . g with current element ; take modulo to avoid overflow ; return the final answer ; function that finds the sum of gcd of all the subsequence of n length ; recursive function that generates the sequence and return the gcd ; 

MOD = 1e9 + 7


def gcd(a, b):
    if (b == 0):
        return a
    else:
        return gcd(b, a % b)


def calculate(pos, g, n, k):
    if (pos == n):
        return g
    answer = 0
    for i in range(1, k + 1):
        answer = (answer % MOD + calculate(pos + 1, gcd(g, i), n, k) % MOD)
        answer %= MOD
    return answer


def sumofGCD(n, k):
    return calculate(0, 0, n, k)


if __name__ == "__main__":
    N = 3
    K = 2
    print(sumofGCD(N, K))

# Expected output:
9.0
# sum of gcd of all possible sequences | python3 implementation of the above approach ; function to find a ^ b in log ( b ) ; function that finds the sum of gcd of all the subsequence of n length ; to stores the number of sequences with gcd i ; find contribution of each gcd to happen ; to count multiples ; possible sequences with overcounting ; to avoid overflow ; find extra element which will not form gcd = i ; find overcounting ; remove the overcounting ; to store the final answer ; return final answer ; 

MOD = (int)(1e9 + 7)


def fastexpo(a, b):
    res = 1
    a = a % MOD
    while (b > 0):
        if ((b & 1) != 0):
            res = (res * a) % MOD
        a = a * a
        a = a % MOD
        b = b >> 1
    return res


def sumofGCD(n, k):
    count = [0] * (k + 1)
    for g in range(k, 0, -1):
        count_multiples = k // g
        temp = fastexpo(count_multiples, n)
        temp = temp % MOD
        extra = 0
        for j in range(g * 2, k + 1, g):
            extra = extra + count[j]
            extra = extra % MOD
        count[g] = temp - extra + MOD
        count[g] = count[g] % MOD
    Sum = 0
    for i in range(1, k + 1):
        add = count[i] % MOD * i % MOD
        add = add % MOD
        Sum = Sum + add
        Sum = Sum % MOD
    return Sum


N, K = 3, 2
print(sumofGCD(N, K))

# Expected output:
9
# split the given string into odds : digit dp | function to check whether a string is an odd number or not ; a function to find the minimum number of segments the given string can be divided such that every segment is a odd number ; declare a splitdp [ ] array and initialize to - 1 ; build the dp table in a bottom - up manner ; initially check if the entire prefix is odd ; if the given prefix can be split into odds then for the remaining string from i to j check if odd . if yes calculate the minimum split till j ; to check if the substring from i to j is a odd number or not ; if it is an odd number , then update the dp array ; return the minimum number of splits for the entire string ; 
def checkOdd(number):
    n = len(number)
    num = ord(number[n - 1]) - 48
    return (num & 1)


def splitIntoOdds(number):
    numLen = len(number)
    splitDP = [-1 for i in range(numLen + 1)]
    for i in range(1, numLen + 1):
        if (i <= 9 and checkOdd(number[0:i]) > 0):
            splitDP[i] = 1
        if (splitDP[i] != -1):
            for j in range(1, 10):
                if (i + j > numLen):
                    break
                if (checkOdd(number[i:i + j])):
                    if (splitDP[i + j] == -1):
                        splitDP[i + j] = 1 + splitDP[i]
                    else:
                        splitDP[i + j] = min(splitDP[i + j], 1 + splitDP[i])
    return splitDP[numLen]


print(splitIntoOdds("123456789123456789123"))

# Expected output:
3
# split the given string into primes : digit dp | function to check whether a string is a prime number or not ; a recursive function to find the minimum number of segments the given string can be divided such that every segment is a prime ; if the number is null ; checkprime function is called to check if the number is a prime or not . ; a very large number denoting maximum ; consider a minimum of 6 and length since the primes are less than 10 ^ 6 ; recursively call the function to check for the remaining string ; evaluating minimum splits into primes for the suffix ; checks if no combination found ; 
def checkPrime(number):
    num = int(number)
    for i in range(2, int(num ** 0.5)):
        if ((num % i) == 0):
            return False
    return True


def splitIntoPrimes(number):
    if (number == ''):
        return 0
    if (len(number) <= 6 and checkPrime(number)):
        return 1
    else:
        numLen = len(number)
        ans = 1000000
        for i in range(1, (min(6, numLen) + 1)):
            if (checkPrime(number[:i])):
                val = splitIntoPrimes(number[i:])
                if (val != -1):
                    ans = min(ans, 1 + val)
        if (ans == 1000000):
            return -1
        return ans


print(splitIntoPrimes("13499315"))
print(splitIntoPrimes("43"))

# Expected output:
3
1