giulio98/xlcost-single-prompt huggingface dataset:
# product of all sorted subsets of size k using elements whose index divide k completely | python3 implementation of the above approach ; iterative function to calculate ( x ^ y ) % p in o ( log y ) ; if y is odd , multiply x with result ; y must be even now ; iterative function to calculate ( ncr ) % p and save in f [ n ] [ r ] ; if j > i then c ( i , j ) = 0 ; if i is equal to j then c ( i , j ) = 1 ; function calculate the final answer ; initialize ans ; x is count of occurence of arr [ i ] in different set such that index of arr [ i ] in those sets divides k completely . ; finding the count of arr [ i ] by placing it at index which divides k completely ; by fermat 's theorem ; 

p = 1000000007


def power(x, y, p):
    res = 1
    x = x % p
    while (y > 0):
        if (y & 1):
            res = (res * x) % p
        y = y >> 1
        x = (x * x) % p
    return res


def nCr(n, p, f, m):
    for i in range(n + 1):
        for j in range(m + 1):
            if (j > i):
                f[i][j] = 0
            elif (j == 0 or j == i):
                f[i][j] = 1
            else:
                f[i][j] = (f[i - 1][j] + f[i - 1][j - 1]) % p


def ProductOfSubsets(arr, n, m):
    f = [[0 for i in range(100)]for j in range(n + 1)]
    nCr(n, p - 1, f, m)
    arr .sort(reverse=False)
    ans = 1
    for i in range(n):
        x = 0
        for j in range(1, m + 1, 1):
            if (m % j == 0):
                x = ((x + (f[n - i - 1][m - j] * f[i][j - 1]) %
                     (p - 1)) % (p - 1))
        ans = ((ans * power(arr[i], x, p)) % p)
    print(ans)


if __name__ == '__main__':
    arr = [4, 5, 7, 9, 3]
    K = 4
    N = len(arr)
    ProductOfSubsets(arr, N, K)

# Expected output:
808556639
# number of ways to write n as a sum of k non | function to count the number of ways to write n as sum of k non - negative integers ; initialise dp [ ] [ ] array ; only 1 way to choose the value with sum k ; initialise sum ; count the ways from previous states ; update the sum ; return the final count of ways ; 
def countWays(n, m):
    dp = [[0 for i in range(n + 1)]for i in range(m + 1)]
    for i in range(n + 1):
        dp[1][i] = 1
    sum = 0
    for i in range(2, m + 1):
        for j in range(n + 1):
            sum = 0
            for k in range(j + 1):
                sum += dp[i - 1][k]
            dp[i][j] = sum
    return dp[m][n]


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

# Expected output:
6
# number of ways to write n as a sum of k non | function to count the number of ways to write n as sum of k non - negative integers ; initialise dp [ ] [ ] array ; fill the dp [ ] [ ] with sum = m ; iterate the dp [ ] [ ] to fill the dp [ ] [ ] array ; condition for first column ; else fill the dp [ ] [ ] with sum till ( i , j ) ; if reach the end , then return the value ; update at current index ; 
def countWays(n, m):
    dp = [[0 for i in range(n + 1)]for j in range(m + 1)]
    for i in range(n + 1):
        dp[1][i] = 1
        if (i != 0):
            dp[1][i] += dp[1][i - 1]
    for i in range(2, m + 1):
        for j in range(n + 1):
            if (j == 0):
                dp[i][j] = dp[i - 1][j]
            else:
                dp[i][j] = dp[i - 1][j]
                if (i == m and j == n):
                    return dp[i][j]
                dp[i][j] += dp[i][j - 1]


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

# Expected output:
6
# longest subsequence such that every element in the subsequence is formed by multiplying previous element with a prime | python3 program to implement the above approach ; function to pre - store primes ; sieve method to check if prime or not ; multiples ; pre - store all the primes ; function to find the longest subsequence ; hash map ; call the function to pre - store the primes ; initialize last element with 1 as that is the longest possible ; iterate from the back and find the longest ; get the number ; initialize dp [ i ] as 1 as the element will only me in the subsequence ; iterate in all the primes and multiply to get the next element ; next element if multiplied with it ; if exceeds the last element then break ; if the number is there in the array ; get the maximum most element ; hash the element ; find the longest ; 

from math import sqrt


def SieveOfEratosthenes(MAX, primes):
    prime = [True] * (MAX + 1)
    for p in range(2, int(sqrt(MAX)) + 1):
        if (prime[p]):
            for i in range(p ** 2, MAX + 1, p):
                prime[i] = False
    for i in range(2, MAX + 1):
        if (prime[i]):
            primes .append(i)


def findLongest(A, n):
    mpp = {}
    primes = []
    SieveOfEratosthenes(A[n - 1], primes)
    dp = [0] * n
    dp[n - 1] = 1
    mpp[A[n - 1]] = n - 1
    for i in range(n - 2, -1, -1):
        num = A[i]
        dp[i] = 1
        maxi = 0
        for it in primes:
            xx = num * it
            if (xx > A[n - 1]):
                break
            elif xx in mpp:
                dp[i] = max(dp[i], 1 + dp[mpp[xx]])
        mpp[A[i]] = i
    ans = 1
    for i in range(n):
        ans = max(ans, dp[i])
    return ans


if __name__ == "__main__":
    a = [1, 2, 5, 6, 12, 35, 60, 385]
    n = len(a)
    print(findLongest(a, n))

# Expected output:
5
# number of binary strings of length n with k adjacent set bits | function to find the number of bit strings of length n with k adjacent set bits ; base case when we form bit string of length n ; if f ( bit string ) = k , count this way ; check if the last bit was set , if it was set then call for next index by incrementing the adjacent bit count else just call the next index with same value of adjacent bit count and either set the bit at current index or let it remain unset ; set the bit at currentindex ; unset the bit at currentindex ; 
def waysToKAdjacentSetBits(n, k, currentIndex, adjacentSetBits, lastBit):
    if (currentIndex == n):
        if (adjacentSetBits == k):
            return 1
        return 0
    noOfWays = 0
    if (lastBit == 1):
        noOfWays += waysToKAdjacentSetBits(n,
                                           k,
                                           currentIndex + 1,
                                           adjacentSetBits + 1,
                                           1)
        noOfWays += waysToKAdjacentSetBits(n,
                                           k,
                                           currentIndex + 1,
                                           adjacentSetBits,
                                           0)
    elif (lastBit != 1):
        noOfWays += waysToKAdjacentSetBits(n,
                                           k,
                                           currentIndex + 1,
                                           adjacentSetBits,
                                           1)
        noOfWays += waysToKAdjacentSetBits(n,
                                           k,
                                           currentIndex + 1,
                                           adjacentSetBits,
                                           0)
    return noOfWays


n = 5
k = 2
totalWays = (
    waysToKAdjacentSetBits(
        n,
        k,
        1,
        0,
        1) +
    waysToKAdjacentSetBits(
        n,
        k,
        1,
        0,
        0))
print("Number of ways =", totalWays)

# Expected output:
Number of ways = 6
# sum of products of all combination taken ( 1 to n ) at a time | find the postfix sum array ; modify the array such that we don 't have to compute the products which are obtained before ; finding sum of all combination taken 1 to n at a time ; sum taken 1 at time is simply sum of 1 - n ; for sum of products for all combination ; finding postfix array ; sum of products taken i + 1 at a time ; modify the array for overlapping problem ; 
def postfix(a, n):
    for i in range(n - 1, 1, -1):
        a[i - 1] = a[i - 1] + a[i]


def modify(a, n):
    for i in range(1, n):
        a[i - 1] = i * a[i]


def allCombination(a, n):
    sum = 0
    for i in range(1, n + 1):
        sum += i
    print("f(1) --> ", sum)
    for i in range(1, n):
        postfix(a, n - i + 1)
        sum = 0
        for j in range(1, n - i + 1):
            sum += (j * a[j])
        print("f(", i + 1, ") --> ", sum)
        modify(a, n)


if __name__ == "__main__":
    n = 5
    a = [0] * n
    for i in range(n):
        a[i] = i + 1
    allCombination(a, n)

# Expected output:
f(1) -->  15
f( 2 ) -->  85
f( 3 ) -->  225
f( 4 ) -->  274
f( 5 ) -->  120
# count ways to reach the nth stair using step 1 , 2 or 3 | returns count of ways to reach n - th stair using 1 or 2 or 3 steps . ; 
def findStep(n):
    if (n == 1 or n == 0):
        return 1
    elif (n == 2):
        return 2
    else:
        return findStep(n - 3) + findStep(n - 2) + findStep(n - 1)


n = 4
print(findStep(n))

# Expected output:
7
# partition problem | dp | a utility function that returns true if there is a subset of arr [ ] with sun equal to given sum ; base cases ; if last element is greater than sum , then ignore it ; else , check if sum can be obtained by any of the following ( a ) including the last element ( b ) excluding the last element ; returns true if arr [ ] can be partitioned in two subsets of equal sum , otherwise false ; calculate sum of the elements in array ; if sum is odd , there cannot be two subsets with equal sum ; find if there is subset with sum equal to half of total sum ; 
def isSubsetSum(arr, n, sum):
    if sum == 0:
        return True
    if n == 0 and sum != 0:
        return False
    if arr[n - 1] > sum:
        return isSubsetSum(arr, n - 1, sum)
    return isSubsetSum(arr, n - 1, sum) or isSubsetSum(arr,
                                                       n - 1, sum - arr[n - 1])


def findPartion(arr, n):
    sum = 0
    for i in range(0, n):
        sum += arr[i]
    if sum % 2 != 0:
        return false
    return isSubsetSum(arr, n, sum // 2)


arr = [3, 1, 5, 9, 12]
n = len(arr)
if findPartion(arr, n):
    print("Can be divided into two subsets of equal sum")
else:
    print("Can not be divided into two subsets of equal sum")

# Expected output:
Can be divided into two subsets of equal sum
# partition problem | dp | returns true if arr [ ] can be partitioned in two subsets of equal sum , otherwise false ; calculate sum of all elements ; initialize the part array as 0 ; fill the partition table in bottom up manner ; the element to be included in the sum cannot be greater than the sum ; check if sum - arr [ i ] could be formed from a subset using elements before index i ; 
def findPartiion(arr, n):
    Sum = 0
    for i in range(n):
        Sum += arr[i]
    if (Sum % 2 != 0):
        return 0
    part = [0] * ((Sum // 2) + 1)
    for i in range((Sum // 2) + 1):
        part[i] = 0
    for i in range(n):
        for j in range(Sum // 2, arr[i] - 1, -1):
            if (part[j - arr[i]] == 1 or j == arr[i]):
                part[j] = 1
    return part[Sum // 2]


arr = [1, 3, 3, 2, 3, 2]
n = len(arr)
if (findPartiion(arr, n) == 1):
    print("Can be divided into two subsets of equal sum")
else:
    print("Can not be divided into two subsets of equal sum")

# Expected output:
Can be divided into two subsets of equal sum
# binomial coefficient | dp | function to find binomial coefficient ; getting the modular inversion for all the numbers from 2 to r with respect to m here m = 1000000007 ; for 1 / ( r ! ) part ; for ( n ) * ( n - 1 ) * ( n - 2 ) * ... * ( n - r + 1 ) part ; 
def binomialCoeff(n, r):
    if (r > n):
        return 0
    m = 1000000007
    inv = [0 for i in range(r + 1)]
    inv[0] = 1
    if r + 1 >= 2:
        inv[1] = 1
    for i in range(2, r + 1):
        inv[i] = m - (m // i) * inv[m % i] % m
    ans = 1
    for i in range(2, r + 1):
        ans = ((ans % m) * (inv[i] % m)) % m
    for i in range(n, n - r, -1):
        ans = ((ans % m) * (i % m)) % m
    return ans


n = 5
r = 2
print("Value of C(", n, ", ", r, ") is ", binomialCoeff(n, r))

# Expected output:
Value of C( 5 ,  2 ) is  10
# check if it is possible to reach ( x , y ) from ( 1 , 1 ) by given steps | function to find the gcd of two numbers ; base case ; recurse ; function to print the answer ; gcd of x and y ; if gcd is power of 2 ; 
def gcd(a, b):
    if (a < b):
        t = a
        a = b
        b = t
    if (a % b == 0):
        return b
    return gcd(b, a % b)


def printAnswer(x, y):
    val = gcd(x, y)
    if ((val & (val - 1)) == 0):
        print("Yes")
    else:
        print("No")


if __name__ == "__main__":
    x = 4
    y = 7
    printAnswer(x, y)

# Expected output:
Yes
# find the element in the matrix generated by given rules | function to return the element in the rth row and cth column from the required matrix ; condition for lower half of matrix ; condition if element is in first row ; starting element of ap in row r ; common difference of ap in row r ; position of element to find in ap in row r ; 
def getElement(N, r, c):
    if (r > c):
        return 0
    if (r == 1):
        return c
    a = (r + 1) * pow(2, r - 2)
    d = pow(2, r - 1)
    c = c - r
    element = a + d * c
    return element


if __name__ == "__main__":
    N = 4
    R = 3
    C = 4
    print(getElement(N, R, C))

# Expected output:
12
# find smallest number formed by inserting given digit | function to insert x in n and return the minimum value string ; variable to store length of string n ; variable to denote the position where x must be added ; if the given string n represent a negative value ; x must be place at the last index where is greater than n [ i ] ; for positive numbers , x must be placed at the last index where it is smaller than n [ i ] ; insert x at that position ; return the string ; 
def MinValue(N, X):
    N = list(N)
    ln = len(N)
    position = ln + 1
    if (N[0] == '-'):
        for i in range(ln - 1, 0, -1):
            if ((ord(N[i]) - ord('0')) < X):
                position = i
    else:
        for i in range(ln - 1, -1, -1):
            if ((ord(N[i]) - ord('0')) > X):
                position = i
    c = chr(X + ord('0'))
    str = N .insert(position, c)
    return ''.join(N)


N = "89"
X = 1
print(MinValue(N, X))

# Expected output:
189
# check if decimal representation of given binary string is divisible by k or not | function to check the binary number is divisible by k ; array poweroftwo will store pow ( 2 , i ) % k ; initializing the first element in array ; storing every pow ( 2 , i ) % k value in the array ; to store the remaining ; iterating till n ; if current bit is 1 ; updating rem ; if completely divisible ; if not completely divisible ; 
def divisibleByk(s, n, k):
    poweroftwo = [0 for i in range(n)]
    poweroftwo[0] = 1 % k
    for i in range(1, n, 1):
        poweroftwo[i] = (poweroftwo[i - 1] * (2 % k)) % k
    rem = 0
    for i in range(n):
        if (s[n - i - 1] == '1'):
            rem += (poweroftwo[i])
            rem %= k
    if (rem == 0):
        return "Yes"
    else:
        return "No"


if __name__ == '__main__':
    s = "1010001"
    k = 9
    n = len(s)
    print(divisibleByk(s, n, k))

# Expected output:
Yes
# count removal of pairs required to be empty all balanced parenthesis subsequences | function to find the maximum count of pairs required to be removed such that subsequence of string does not contain any valid parenthesis ; stores count of pairs of balanced parenthesis ; stores count of curly balanced parenthesis ; stores count of small balanced parenthesis ; stores count of square balanced parenthesis ; iterate over characters of the string ; update cntcurly ; update cntsml ; update cntsqr ; update cntcurly ; update cntpairs ; update cntsml ; update cntpairs ; update cntsml ; update cntpairs ; 
def cntBalancedParenthesis(s, N):
    cntPairs = 0
    cntCurly = 0
    cntSml = 0
    cntSqr = 0
    for i in range(N):
        if (ord(s[i]) == ord('{')):
            cntCurly += 1
        elif (ord(s[i]) == ord('(')):
            cntSml += 1
        elif (ord(s[i]) == ord('[')):
            cntSqr += 1
        elif (ord(s[i]) == ord('}') and cntCurly > 0):
            cntCurly -= 1
            cntPairs += 1
        elif (ord(s[i]) == ord(')') and cntSml > 0):
            cntSml -= 1
            cntPairs += 1
        elif (ord(s[i]) == ord(']') and cntSqr > 0):
            cntSqr -= 1
            cntPairs += 1
    print(cntPairs)


if __name__ == '__main__':
    s = "{(})"
    N = len(s)
    cntBalancedParenthesis(s, N)

# Expected output:
2
# count of strings that does not contain arc intersection | function to check if there is arc intersection or not ; traverse the string s ; insert all the elements in the stack one by one ; extract the top element ; pop out the top element ; check if the top element is same as the popped element ; otherwise ; if the stack is empty ; function to check if there is arc intersection or not for the given array of strings ; stores count of string not having arc intersection ; iterate through array ; length of every string ; function call ; print the desired count ; 
def arcIntersection(S, lenn):
    stk = []
    for i in range(lenn):
        stk .append(S[i])
        if (len(stk) >= 2):
            temp = stk[-1]
            del stk[-1]
            if (stk[-1] == temp):
                del stk[-1]
            else:
                stk .append(temp)
    if (len(stk) == 0):
        return 1
    return 0


def countString(arr, N):
    count = 0
    for i in range(N):
        lenn = len(arr[i])
        count += arcIntersection(arr[i], lenn)
    print(count)


if __name__ == '__main__':
    arr = ["0101", "0011", "0110"]
    N = len(arr)
    countString(arr, N)

# Expected output:
2
# check if decimal representation of binary string is divisible by 9 or not | function to convert the binary string into octal representation ; stores binary representation of the decimal value [ 0 - 7 ] ; stores the decimal values of binary strings [ 0 - 7 ] ; stores length of s ; update s ; update s ; update n ; stores octal representation of the binary string ; traverse the binary string ; stores 3 consecutive characters of the binary string ; append octal representation of temp ; function to check if binary string is divisible by 9 or not ; stores octal representation of s ; stores sum of elements present at odd positions of oct ; stores sum of elements present at odd positions of oct ; stores length of oct ; traverse the string oct ; update oddsum ; traverse the string oct ; update evensum ; stores cotal representation of 9 ; if absolute value of ( oddsum - evensum ) is divisible by oct_9 ; 
def ConvertequivalentBase8(S):
    mp = {}
    mp["000"] = '0'
    mp["001"] = '1'
    mp["010"] = '2'
    mp["011"] = '3'
    mp["100"] = '4'
    mp["101"] = '5'
    mp["110"] = '6'
    mp["111"] = '7'
    N = len(S)
    if (N % 3 == 2):
        S = "0" + S
    elif (N % 3 == 1):
        S = "00" + S
    N = len(S)
    octal = ""
    for i in range(0, N, 3):
        temp = S[i:i + 3]
        if temp in mp:
            octal += (mp[temp])
    return octal


def binString_div_9(S, N):
    octal = ConvertequivalentBase8(S)
    oddSum = 0
    evenSum = 0
    M = len(octal)
    for i in range(0, M, 2):
        oddSum += ord(octal[i]) - ord('0')
    for i in range(1, M, 2):
        evenSum += ord(octal[i]) - ord('0')
    Oct_9 = 11
    if (abs(oddSum - evenSum) % Oct_9 == 0):
        return "Yes"
    return "No"


if __name__ == "__main__":
    S = "1010001"
    N = len(S)
    print(binString_div_9(S, N))

# Expected output:
Yes
# minimum cost to remove the spaces between characters of a string by rearranging the characters | function to calculate the minimum cost ; stores the minimum cost ; stores the count of characters found ; stores the count of blank spaces found ; stores the count of total characters ; if the count of characters is equal to 1 ; iterate over the string ; consider the previous character together with current character ; if not together already ; add the cost to group them together ; increase count of characters found ; otherwise ; increase count of spaces found ; return the total cost obtained ; 
def min_cost(S):
    cost = 0
    F = 0
    B = 0
    n = len(S) - S .count(' ')
    if n == 1:
        return cost
    for char in S:
        if char != ' ':
            if B != 0:
                cost += min(n - F, F) * B
                B = 0
            F += 1
        else:
            B += 1
    return cost


S = " @TABSYMBOL$"
print(min_cost(S))

# Expected output:
0
# minimize cost to replace all the vowels of a given string by a single vowel | function that return true if the given character is a vowel ; function to return the minimum cost to convert all the vowels of a string to a single one ; stores count of respective vowels ; iterate through the string ; if a vowel is encountered ; calculate the cost ; return the minimum cost ; 
def isVowel(ch):
    if (ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u'):
        return True
    else:
        return False


def minCost(S):
    cA = 0
    cE = 0
    cI = 0
    cO = 0
    cU = 0
    for i in range(len(S)):
        if (isVowel(S[i])):
            cA += abs(ord(S[i]) - ord('a'))
            cE += abs(ord(S[i]) - ord('e'))
            cI += abs(ord(S[i]) - ord('i'))
            cO += abs(ord(S[i]) - ord('o'))
            cU += abs(ord(S[i]) - ord('u'))
    return min(min(min(min(cA, cE), cI), cO), cU)


S = "geeksforgeeks"
print(minCost(S))

# Expected output:
10
# generate a string whose all k | function to return the required required string ; iterate the given string ; append the first character of every substring of length k ; consider all characters from the last substring ; 
def decode_String(st, K):
    ans = ""
    for i in range(0, len(st), K):
        ans += st[i]
    for i in range(len(st) - (K - 1), len(st)):
        ans += st[i]
    print(ans)


if __name__ == "__main__":
    K = 3
    st = "abcbcscsesesesd"
    decode_String(st, K)

# Expected output:
abcsesd
# lexicographically smallest k | function that prints the lexicographically smallest k - length substring containing maximum number of vowels ; store the length of the string ; initialize a prefix sum array ; loop through the string to create the prefix sum array ; store 1 at the index if it is a vowel ; otherwise , store 0 ; process the prefix array ; initialize the variable to store maximum count of vowels ; initialize the variable to store substring with maximum count of vowels ; loop through the prefix array ; store the current count of vowels ; update the result if current count is greater than maximum count ; update lexicographically smallest substring if the current count is equal to the maximum count ; return the result ; 
def maxVowelSubString(str1, K):
    N = len(str1)
    pref = [0 for i in range(N)]
    for i in range(N):
        if (str1[i] == 'a' or str1[i] == 'e' or str1[i]
                == 'i' or str1[i] == 'o' or str1[i] == 'u'):
            pref[i] = 1
        else:
            pref[i] = 0
        if (i):
            pref[i] += pref[i - 1]
    maxCount = pref[K - 1]
    res = str1[0:K]
    for i in range(K, N):
        currCount = pref[i] - pref[i - K]
        if (currCount > maxCount):
            maxCount = currCount
            res = str1[i - K + 1:i + 1]
        elif (currCount == maxCount):
            temp = str1[i - K + 1:i + 1]
            if (temp < res):
                res = temp
    return res


if __name__ == '__main__':
    str1 = "ceebbaceeffo"
    K = 3
    print(maxVowelSubString(str1, K))

# Expected output:
ace