giulio98/xlcost-single-prompt huggingface dataset:
# number of subsequences with even and odd sum | returns the count of odd and even subsequences ; initialising count_even and count_odd to 0 since as there is no subsequence before the iteration with even or odd count . ; find sum of all subsequences with even count and odd count and storing them as we iterate . ; if the number is even ; if the number is odd ; 
def countSum(arr, n):
    result = 0
    count_odd = 0
    count_even = 0
    for i in range(1, n + 1):
        if (arr[i - 1] % 2 == 0):
            count_even = count_even + count_even + 1
            count_odd = count_odd + count_odd
        else:
            temp = count_even
            count_even = count_even + count_odd
            count_odd = count_odd + temp + 1
    return (count_even, count_odd)


arr = [1, 2, 2, 3]
n = len(arr)
count_even, count_odd = countSum(arr, n)
print("EvenSum = ", count_even, " OddSum = ", count_odd)

# Expected output:
EvenSum =  7  OddSum =  8
# count of integers of length n and value less than k such that they contain digits only from the given set | python3 implementation of the approach ; function to convert a number into vector ; push all the digits of n from the end one by one to the vector ; if the original number was 0 ; reverse the vector elements ; return the required vector ; function to return the count of b length integers which are less than c and they contain digits from set a [ ] only ; convert number to digit array ; case 1 : no such number possible as the generated numbers will always be greater than c ; case 2 : all integers of length b are valid as they all are less than c ; contain 0 ; case 3 ; update the lower [ ] array such that lower [ i ] stores the count of elements in a [ ] which are less than i ; for first index we can 't use 0 ; whether ( i - 1 ) digit of generated number can be equal to ( i - 1 ) digit of c ; is digit [ i - 1 ] present in a ? ; 

MAX = 10


def numToVec(N):
    digit = []
    while (N != 0):
        digit .append(N % 10)
        N = N // 10
    if (len(digit) == 0):
        digit .append(0)
    digit = digit[::-1]
    return digit


def solve(A, B, C):
    d, d2 = 0, 0
    digit = numToVec(C)
    d = len(A)
    if (B > len(digit) or d == 0):
        return 0
    elif (B < len(digit)):
        if (A[0] == 0 and B != 1):
            return (d - 1) * pow(d, B - 1)
        else:
            return pow(d, B)
    else:
        dp = [0 for i in range(B + 1)]
        lower = [0 for i in range(MAX + 1)]
        for i in range(d):
            lower[A[i] + 1] = 1
        for i in range(1, MAX + 1):
            lower[i] = lower[i - 1] + lower[i]
        flag = True
        dp[0] = 0
        for i in range(1, B + 1):
            d2 = lower[digit[i - 1]]
            dp[i] = dp[i - 1] * d
            if (i == 1 and A[0] == 0 and B != 1):
                d2 = d2 - 1
            if (flag):
                dp[i] += d2
            flag = (flag & (lower[digit[i - 1] + 1]
                    == lower[digit[i - 1]] + 1))
        return dp[B]


A = [0, 1, 2, 5]
N = 2
k = 21
print(solve(A, N, k))

# Expected output:
5
# number of paths of weight w in a k | python 3 program to count the number of paths with weight w in a k - ary tree ; function to return the number of ways having weight as wt in k - ary tree ; return 0 if weight becomes less than zero ; return one only if the current path has included edge weight of atleast m ; if the current edge weight is greater than or equal to m , set used as true ; 

import numpy as np


def solve(dp, wt, K, M, used):
    if (wt < 0):
        return 0
    if (wt == 0):
        if (used):
            return 1
        return 0
    if (dp[wt][used] != -1):
        return dp[wt][used]
    ans = 0
    for i in range(1, K + 1):
        if (i >= M):
            ans += solve(dp, wt - i, K, M, used | 1)
        else:
            ans += solve(dp, wt - i, K, M, used)
    dp[wt][used] = ans
    return ans


if __name__ == "__main__":
    W = 3
    K = 3
    M = 2
    dp = np .ones((W + 1, 2))
    dp = -1 * dp
    print(solve(dp, W, K, M, 0))

# Expected output:
3
# ways to write n as sum of two or more positive integers | set | function to find the number of partitions of n ; base case ; 
def partitions(n):
    p = [0] * (n + 1)
    p[0] = 1
    for i in range(1, n + 1):
        k = 1
        while ((k * (3 * k - 1)) / 2 <= i):
            p[i] += ((1 if k % 2 else -1) * p[i - (k * (3 * k - 1)) // 2])
            if (k > 0):
                k *= -1
            else:
                k = 1 - k
    return p[n]


if __name__ == "__main__":
    N = 20
    print(partitions(N))

# Expected output:
627
# longest increasing path in matrix | python3 program to find longest increasing path in a matrix . ; return the length of lip in 2d matrix ; if value not calculated yet . ; if reach bottom left cell , return 1. ; if reach the corner of the matrix . ; if value greater than below cell . ; if value greater than left cell . ; wrapper function ; 

MAX = 20


def LIP(dp, mat, n, m, x, y):
    if (dp[x][y] < 0):
        result = 0
        if (x == n - 1 and y == m - 1):
            dp[x][y] = 1
            return dp[x][y]
        if (x == n - 1 or y == m - 1):
            result = 1
        if (x + 1 < n and mat[x][y] < mat[x + 1][y]):
            result = 1 + LIP(dp, mat, n, m, x + 1, y)
        if (y + 1 < m and mat[x][y] < mat[x][y + 1]):
            result = max(result, 1 + LIP(dp, mat, n, m, x, y + 1))
        dp[x][y] = result
    return dp[x][y]


def wrapper(mat, n, m):
    dp = [[-1 for i in range(MAX)]for i in range(MAX)]
    return LIP(dp, mat, n, m, 0, 0)


mat = [[1, 2, 3, 4], [2, 2, 3, 4], [3, 2, 3, 4], [4, 5, 6, 7]]
n = 4
m = 4
print(wrapper(mat, n, m))

# Expected output:
7
# counts paths from a point to reach origin | recursive function to count number of paths ; if we reach bottom or top left , we are have only one way to reach ( 0 , 0 ) ; else count sum of both ways ; 
def countPaths(n, m):
    if (n == 0 or m == 0):
        return 1
    return (countPaths(n - 1, m) + countPaths(n, m - 1))


n = 3
m = 2
print(" Number of Paths ", countPaths(n, m))

# Expected output:
 Number of Paths  10
# gold mine problem | python program to solve gold mine problem ; returns maximum amount of gold that can be collected when journey started from first column and moves allowed are right , right - up and right - down ; create a table for storing intermediate results and initialize all cells to 0. the first row of goldminetable gives the maximum gold that the miner can collect when starts that row ; gold collected on going to the cell on the right ( -> ) ; gold collected on going to the cell to right up ( / ) ; gold collected on going to the cell to right down ( \ ) ; max gold collected from taking either of the above 3 paths ; the max amount of gold collected will be the max value in first column of all rows ; 

MAX = 100


def getMaxGold(gold, m, n):
    goldTable = [[0 for i in range(n)]for j in range(m)]
    for col in range(n - 1, -1, -1):
        for row in range(m):
            if (col == n - 1):
                right = 0
            else:
                right = goldTable[row][col + 1]
            if (row == 0 or col == n - 1):
                right_up = 0
            else:
                right_up = goldTable[row - 1][col + 1]
            if (row == m - 1 or col == n - 1):
                right_down = 0
            else:
                right_down = goldTable[row + 1][col + 1]
            goldTable[row][col] = gold[row][col] + \
                max(right, right_up, right_down)
    res = goldTable[0][0]
    for i in range(1, m):
        res = max(res, goldTable[i][0])
    return res


gold = [[1, 3, 1, 5], [2, 2, 4, 1], [5, 0, 2, 3], [0, 6, 1, 2]]
m = 4
n = 4
print(getMaxGold(gold, m, n))

# Expected output:
16
# find minimum adjustment cost of an array | python3 program to find minimum adjustment cost of an array ; function to find minimum adjustment cost of an array ; dp [ i ] [ j ] stores minimal adjustment cost on changing a [ i ] to j ; handle first element of array separately ; do for rest elements of the array ; replace a [ i ] to j and calculate minimal adjustment cost dp [ i ] [ j ] ; initialize minimal adjustment cost to int_max ; consider all k such that k >= max ( j - target , 0 ) and k <= min ( m , j + target ) and take minimum ; return minimum value from last row of dp table ; 

M = 100


def minAdjustmentCost(A, n, target):
    dp = [[0 for i in range(M + 1)]for i in range(n)]
    for j in range(M + 1):
        dp[0][j] = abs(j - A[0])
    for i in range(1, n):
        for j in range(M + 1):
            dp[i][j] = 100000000
            for k in range(max(j - target, 0), min(M, j + target) + 1):
                dp[i][j] = min(dp[i][j], dp[i - 1][k] + abs(A[i] - j))
    res = 10000000
    for j in range(M + 1):
        res = min(res, dp[n - 1][j])
    return res


arr = [55, 77, 52, 61, 39, 6, 25, 60, 49, 47]
n = len(arr)
target = 10
print("Minimum adjustment cost is", minAdjustmentCost(arr, n, target), sep=' ')

# Expected output:
Minimum adjustment cost is 75
# count triplets from a given range having sum of two numbers of a triplet equal to the third number | function to find the number of triplets from the range [ l , r ] having sum of two numbers from the triplet equal to the third number ; stores the total number of triplets ; find the difference of the range ; case 1 : if triplets can 't  be formed, then return 0 ; otherwise ; update the total number of triplets ; return the count ; 
def totalCombination(L, R):
    count = 0
    K = R - L
    if (K < L):
        return 0
    ans = K - L
    count = ((ans + 1) * (ans + 2)) // 2
    return count


if __name__ == '__main__':
    L, R = 2, 6
    print(totalCombination(L, R))

# Expected output:
6
# construct two n | function to generate two arrays satisfying the given conditions ; declare the two arrays a and b ; iterate from range [ 1 , 2 * n ] ; assign consecutive numbers to same indices of the two arrays ; print the first array ; print the second array , b ; 
def printArrays(n):
    A, B = [], []
    for i in range(1, 2 * n + 1):
        if (i % 2 == 0):
            A .append(i)
        else:
            B .append(i)
    print("{ ", end="")
    for i in range(n):
        print(A[i], end="")
        if (i != n - 1):
            print(", ", end="")
    print("}")
    print("{ ", end="")
    for i in range(n):
        print(B[i], end="")
        if (i != n - 1):
            print(",", end=" ")
    print(" }", end="")


if __name__ == "__main__":
    N = 5
    printArrays(N)

# Expected output:
{ 2, 4, 6, 8, 10}
{ 1, 3, 5, 7, 9 }
# numbers formed by flipping common set bits in two given integers | function to flip bits of a and b which are set in both of them ; iterate all possible bits of a and b ; if ith bit is set in both a and b ; clear i - th bit of a ; clear i - th bit of b ; print a and b ; 
def flipBitsOfAandB(A, B):
    for i in range(0, 32):
        if ((A & (1 << i)) and (B & (1 << i))):
            A = A ^ (1 << i)
            B = B ^ (1 << i)
    print(A, B)


if __name__ == "__main__":
    A = 7
    B = 4
    flipBitsOfAandB(A, B)

# Expected output:
3 0
# count of distinct pair sum between two 1 to n value arrays | function to find the distinct sums ; 
def findDistinctSums(N):
    return (2 * N - 1)


N = 3
print(findDistinctSums(N))

# Expected output:
5
# count of substrings from given ternary strings containing characters at least once | function to count the number of substrings consists of 0 , 1 , and 2 ; initialize frequency array of size 3 ; stores the resultant count ; traversing string str ; update frequency array ; if all the characters are present counting number of substrings possible ; update number of substrings ; return the number of substrings ; 
def countSubstrings(str):
    freq = [0] * 3
    count = 0
    i = 0
    for j in range(0, len(str)):
        freq[ord(str[j]) - ord('0')] += 1
        while (freq[0] > 0 and freq[1] > 0 and freq[2] > 0):
            i += 1
            freq[ord(str[i]) - ord('0')] -= 1
        count += i
    return count


str = "00021"
count = countSubstrings(str)
print(count)

# Expected output:
3
# minimum flips to remove any consecutive 3 0 s or 1 s in given binary string | function to find the minimum number of flips to make all three pairs of consecutive characters different ; stores resultant count of pairs ; base case ; iterate over the range [ 0 , n - 2 ] ; if the consecutive 3 numbers are the same then increment the count and the counter ; return the answer ; 
def minFlips(st):
    count = 0
    if (len(st) <= 2):
        return 0
    for i in range(len(st) - 2):
        if (st[i] == st[i + 1] and st[i + 2] == st[i + 1]):
            i = i + 3
            count += 1
        else:
            i += 1
    return count


if __name__ == "__main__":
    S = "0011101"
    print(minFlips(S))

# Expected output:
1
# encrypt the string | function to convert decimal to hex ; function to encrypt the string ; iterate the characters of the string ; iterate until s [ i ] is equal to ch ; update count and i ; decrement i by 1 ; convert count to hexadecimal representation ; append the character ; append the characters frequency in hexadecimal representation ; reverse the obtained answer ; return required answer ; 
def convertToHex(num):
    temp = ""
    while (num != 0):
        rem = num % 16
        c = 0
        if (rem < 10):
            c = rem + 48
        else:
            c = rem + 87
        temp += chr(c)
        num = num // 16
    return temp


def encryptString(S, N):
    ans = ""
    for i in range(N):
        ch = S[i]
        count = 0
        while (i < N and S[i] == ch):
            count += 1
            i += 1
        i -= 1
        hex = convertToHex(count)
        ans += ch
        ans += hex
    ans = ans[::-1]
    return ans


if __name__ == '__main__':
    S = "abc"
    N = len(S)
    print(encryptString(S, N))

# Expected output:
1c1b1a
# count of binary strings of length n such that frequency of 1 ' s ▁ exceeds ▁ frequency ▁ of ▁ 0' s | function to calculate and return 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 binary strings of length n such that frequency of 1 ' s ▁ exceed ▁ that ▁ of ▁ 0' s ; count of n - length binary strings ; count of n - length binary strings having equal count of 0 ' s ▁ and ▁ 1' s ; for even length strings ; 
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 countOfString(N):
    Stotal = pow(2, N)
    Sequal = 0
    if (N % 2 == 0):
        Sequal = binomialCoeff(N, N // 2)
    S1 = (Stotal - Sequal) // 2
    return S1


N = 3
print(countOfString(N))

# Expected output:
4
# remove all occurrences of a character in a string | recursive approach | function to remove all occurrences of a character in the string ; base case ; check the first character of the given string ; pass the rest of the string to recursion function call ; add the first character of str and string from recursion ; given string ; 
def removeCharRecursive(str, X):
    if (len(str) == 0):
        return ""
    if (str[0] == X):
        return removeCharRecursive(str[1:], X)
    return str[0] + removeCharRecursive(str[1:], X)


str = "geeksforgeeks"
X = 'e'
str = removeCharRecursive(str, X)
print(str)

# Expected output:
gksforgks
# maximum time such that absolute difference between hour and minute lies in given range | function checks whether 
def isValid(a1, a2, strr, flag):
    v1, v2 = 0, 0
    if (flag == 0):
        v1 = strr[4]
        v2 = strr[3]
    else:
        v1 = strr[1]
        v2 = strr[0]
    if (v1 != a1 and v1 != '?'):
        return False
    if (v2 != a2 and v2 != '?'):
        return False
    return True


def inRange(hh, mm, L, R):
    a = abs(hh - mm)
    if (a < L or a > R):
        return False
    return True


def displayTime(hh, mm):
    if (hh > 10):
        print(hh, end=":")
    elif (hh < 10):
        print("0", hh, end=":")
    if (mm > 10):
        print(mm)
    elif (mm < 10):
        print("0", mm)


def maximumTimeWithDifferenceInRange(strr, L, R):
    i, j = 0, 0
    h1, h2, m1, m2 = 0, 0, 0, 0
    for i in range(23, -1, -1):
        h1 = i % 10
        h2 = i // 10
        if (not isValid(chr(h1), chr(h2), strr, 1)):
            continue
        for j in range(59, -1, -1):
            m1 = j % 10
            m2 = j // 10
            if (not isValid(chr(m1), chr(m2), strr, 0)):
                continue
            if (inRange(i, j, L, R)):
                displayTime(i, j)
                return
    if (inRange(i, j, L, R)):
        displayTime(i, j)
    else:
        print(-1)


timeValue = "??:??"
L = 20
R = 39
maximumTimeWithDifferenceInRange(timeValue, L, R)

# Expected output:
23:59
# check if a string can be split into even length palindromic substrings | function to check string str can be split a string into even length palindromic substrings ; initialize a stack ; iterate the string ; if the i - th character is same as that at the top of the stack then pop the top element ; else push the current charactor into the stack ; if the stack is empty , then even palindromic substrings are possible ; else not - possible ; 
def check(s, n):
    st = []
    for i in range(n):
        if (len(st) != 0 and st[len(st) - 1] == s[i]):
            st .pop()
        else:
            st .append(s[i])
    if (len(st) == 0):
        return True
    else:
        return False


str = "aanncddc"
n = len(str)
if (check(str, n)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# number of strings in two array satisfy the given conditions | python3 program for the above approach ; to store the frequency of string after bitmasking ; to store result for each string in arr2 [ ] ; traverse the arr1 [ ] and bitmask each string in it ; bitmasking for each string s ; update the frequency of string with it 's bitmasking value ; traverse the arr2 [ ] ; bitmasking for each string s ; check if temp is present in an unordered_map or not ; check for next set bit ; push the count for current string in resultant array ; print the count for each string ; 

from collections import defaultdict


def findNumOfValidWords(w, p):
    m = defaultdict(int)
    res = []
    for s in w:
        val = 0
        for c in s:
            val = val | (1 << (ord(c) - ord('a')))
        m[val] += 1
    for s in p:
        val = 0
        for c in s:
            val = val | (1 << (ord(c) - ord('a')))
        temp = val
        first = ord(s[0]) - ord('a')
        count = 0
        while (temp != 0):
            if (((temp >> first) & 1) == 1):
                if (temp in m):
                    count += m[temp]
            temp = (temp - 1) & val
        res .append(count)
    for it in res:
        print(it)


if __name__ == "__main__":
    arr1 = ["aaaa", "asas", "able", "ability", "actt", "actor", "access"]
    arr2 = ["aboveyz", "abrodyz", "absolute", "absoryz", "actresz", "gaswxyz"]
    findNumOfValidWords(arr1, arr2)

# Expected output:
1
1
3
2
4
0
# maximize the decimal equivalent by flipping only a contiguous set of 0 s | function to print the binary number ; check if the current number is 0 ; find the continuous 0 s ; replace initially occurring 0 with 1 ; return the string and break the loop ; 
def flip(s):
    s = list(s)
    for i in range(len(s)):
        if (s[i] == '0'):
            while (s[i] == '0'):
                s[i] = '1'
                i += 1
            s = ''.join(map(str, s))
            return s


s = "100010001"
print(flip(s))

# Expected output:
111110001
# sentence case of a given camel cased string | function to return the original string after converting it back from camelcase ; print the first character as it is ; traverse the rest of the characters one by one ; if current character is uppercase prspace followed by the current character in lowercase ; else print the current character ; 
def getOrgString(s):
    print(s[0], end="")
    i = 1
    while (i < len(s)):
        if (ord(s[i]) >= ord('A') and ord(s[i]) <= ord('Z')):
            print(" ", s[i].lower(), end="")
        else:
            print(s[i], end="")
        i += 1


s = "ILoveGeeksForGeeks"
getOrgString(s)

# Expected output:
I  love  geeks  for  geeks
# count occurrences of a character in a repeated string | function to count the character 'a ; atleast k repetition are required ; if n is not the multiple of the string size check for the remaining repeating character . ; 
def countChar(str, x):
    count = 0
    for i in range(len(str)):
        if (str[i] == x):
            count += 1
    n = 10
    repetitions = n // len(str)
    count = count * repetitions
    l = n % len(str)
    for i in range(l):
        if (str[i] == x):
            count += 1
    return count


str = "abcac"
print(countChar(str, 'a'))

# Expected output:
4
# frequency measuring techniques for competitive programming | python3 program to count frequencies of array items having small values . ; create an array to store counts . the size of array is limit + 1 and all values are initially 0 ; traverse through array elements and count frequencies ( assuming that elements are limited by limit ) ; 
def countFreq(arr, n, limit):
    count = [0 for i in range(limit + 1)]
    for i in range(n):
        count[arr[i]] += 1
    for i in range(limit + 1):
        if (count[i] > 0):
            print(i, count[i])


arr = [5, 5, 6, 6, 5, 6, 1, 2, 3, 10, 10]
n = len(arr)
limit = 10
countFreq(arr, n, limit)

# Expected output:
1 1
2 1
3 1
5 3
6 3
10 2
# check if a string has m consecutive 1 ' s ▁ or ▁ 0' s | function that checks if the binary string contains m consecutive 1 ' s ▁ or ▁ 0' s ; length of binary string ; counts zeros ; counts 1 's ; count consecutive 0 's ; count consecutive 1 's ; 
def check(s, m):
    l = len(s)
    c1 = 0
    c2 = 0
    for i in range(0, l - 1):
        if (s[i] == '0'):
            c2 = 0
            c1 = c1 + 1
        else:
            c1 = 0
            c2 = c2 + 1
        if (c1 == m or c2 == m):
            return True
    return False


s = "001001"
m = 2
if (check(s, m)):
    print("YES")
else:
    print("NO")

# Expected output:
YES
# product of nodes at k | function to find product of digits of elements at k - th level ; initialize result ; increasing level number ; decreasing level number ; check if current level is the desired level or not ; required product ; 
def productAtKthLevel(tree, k):
    level = -1
    product = 1
    n = len(tree)
    for i in range(0, n):
        if (tree[i] == '('):
            level += 1
        elif (tree[i] == ')'):
            level -= 1
        else:
            if (level == k):
                product *= (int(tree[i]) - int('0'))
    return product


tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))"
k = 2
print(productAtKthLevel(tree, k))

# Expected output:
72
# removing row or column wise duplicates from matrix of characters | function to check duplicates in row and column ; create an array ispresent and initialize all entries of it as false . the value of ispresent [ i ] [ j ] is going to be true if s [ i ] [ j ] is present in its row or column . ; checking every row for duplicates of a [ i ] [ j ] ; checking every row for duplicates of a [ i ] [ j ] ; if the character is unique in its row and column ; 
def findDuplicates(a, n, m):
    isPresent = [[False for i in range(n)]for j in range(m)]
    for i in range(n):
        for j in range(m):
            for k in range(n):
                if i != k and a[i][j] == a[k][j]:
                    isPresent[i][j] = True
                    isPresent[k][j] = True
            for k in range(m):
                if j != k and a[i][j] == a[i][k]:
                    isPresent[i][j] = True
                    isPresent[i][k] = True
    for i in range(n):
        for j in range(m):
            if not isPresent[i][j]:
                print(a[i][j], end="")


if __name__ == "__main__":
    n = 2
    m = 2
    a = ["zx", "xz"]
    findDuplicates(a, n, m)

# Expected output:
zxxz