giulio98/xlcost-single-prompt huggingface dataset:
# generate an n | function to calculate gcd of given array ; function to calculate gcd of two integers ; utility function to check for all the combinations ; if a sequence of size n is obtained ; if gcd of current combination is k ; if current element from first array is divisible by k ; recursively proceed further ; if current combination satisfies given condition ; remove the element from the combination ; if current element from second array is divisible by k ; recursively proceed further ; if current combination satisfies given condition ; remove the element from the combination ; function to check for all possible combinations ; stores the subsequence ; if gcd of any sequence is not equal to k ; given arrays ; 
def GCDArr(a):
    ans = a[0]
    for i in a:
        ans = GCD(ans, i)
    return ans


def GCD(a, b):
    if not b:
        return a
    return GCD(b, a % b)


def findSubseqUtil(a, b, ans, k, i):
    if len(ans) == len(a):
        if GCDArr(ans) == k:
            print(ans)
            return True
        else:
            return False
    if not a[i] % K:
        ans .append(a[i])
        temp = findSubseqUtil(a, b, ans, k, i + 1)
        if temp:
            return True
        ans .pop()
    if not b[i] % k:
        ans .append(b[i])
        temp = findSubseqUtil(a, b, ans, k, i + 1)
        if temp:
            return True
        ans .pop()
    return False


def findSubseq(A, B, K, i):
    ans = []
    findSubseqUtil(A, B, ans, K, i)
    if not ans:
        print(-1)


A = [5, 3, 6, 2, 9]
B = [21, 7, 14, 12, 28]
K = 3
ans = findSubseq(A, B, K, 0)

# Expected output:
[21, 3, 6, 12, 9]
# kth element in permutation of first n natural numbers having all even numbers placed before odd numbers in increasing order | function to find the k - th element in the required permutation ; stores the required permutation ; insert all the even numbers less than or equal to n ; now , insert all odd numbers less than or equal to n ; print the kth element ; 
def findKthElement(N, K):
    v = []
    for i in range(1, N + 1):
        if (i % 2 == 0):
            v .append(i)
    for i in range(1, N + 1):
        if (i % 2 != 0):
            v .append(i)
    print(v[K - 1])


if __name__ == "__main__":
    N = 10
    K = 3
    findKthElement(N, K)

# Expected output:
6
# minimum subsequences of a string a required to be appended to obtain the string b | python3 program for the above approach ; function to count the minimum subsequences of a a required to be appended to obtain the b ; size of the string ; maps characters to their respective indices ; insert indices of characters into the sets ; stores the position of the last visited index in the a . initially set it to - 1. ; stores the required count ; iterate over the characters of b ; if the character in b is not present in a , return - 1 ; fetch the next index from b [ i ] 's set ; if the iterator points to the end of that set ; if it doesn 't poto the  end, update previous ; prthe answer ; 

from bisect import bisect_right


def countminOpsToConstructAString(A, B):
    N = len(A)
    i = 0
    mp = [[]for i in range(26)]
    for i in range(N):
        mp[ord(A[i]) - ord('a')].append(i)
    previous = -1
    ans, i = 1, 0
    while i < len(B):
        ch = B[i]
        if (len(mp[ord(ch) - ord('a')]) == 0):
            print(-1)
            return
        it = bisect_right(mp[ord(ch) - ord('a')], previous)
        if (it == len(mp[ord(ch) - ord('a')])):
            previous = -1
            ans += 1
            continue
        previous = mp[ord(ch) - ord('a')][it]
        i += 1
    print(ans)


if __name__ == '__main__':
    A, B = "abc", "abac"
    countminOpsToConstructAString(A, B)

# Expected output:
2
# maximize difference between odd and even indexed array elements by shift operations | function to minimize array elements by shift operations ; for checking all the left shift operations ; left shift ; consider the minimum possible value ; function to maximize array elements by shift operations ; for checking all the left shift operations ; left shift ; consider the maximum possible value ; function to maximize the absolute difference between even and odd indexed array elements ; to calculate the difference of odd indexed elements and even indexed elements ; to calculate the difference between odd and even indexed array elements ; print the maximum value ; 
def minimize(n):
    optEle = n
    strEle = str(n)
    for idx in range(len(strEle)):
        temp = int(strEle[idx:] + strEle[:idx])
        optEle = min(optEle, temp)
    return optEle


def maximize(n):
    optEle = n
    strEle = str(n)
    for idx in range(len(strEle)):
        temp = int(strEle[idx:] + strEle[:idx])
        optEle = max(optEle, temp)
    return optEle


def minimumDifference(arr):
    caseOne = 0
    minVal = 0
    maxVal = 0
    for i in range(len(arr)):
        if i % 2:
            minVal += minimize(arr[i])
        else:
            maxVal += maximize(arr[i])
    caseOne = abs(maxVal - minVal)
    caseTwo = 0
    minVal = 0
    maxVal = 0
    for i in range(len(arr)):
        if i % 2:
            maxVal += maximize(arr[i])
        else:
            minVal += minimize(arr[i])
    caseTwo = abs(maxVal - minVal)
    print(max(caseOne, caseTwo))


arr = [332, 421, 215, 584, 232]
minimumDifference(arr)

# Expected output:
658
# find if given vertical level of binary tree is sorted or not | python program to determine whether vertical level l of binary tree is sorted or not . ; structure of a tree node . ; helper function to determine if vertical level l of given binary tree is sorted or not . ; if root is null , then the answer is an empty subset and an empty subset is always considered to be sorted . ; variable to store previous value in vertical level l . ; variable to store current level while traversing tree vertically . ; variable to store current node while traversing tree vertically . ; declare queue to do vertical order traversal . a pair is used as element of queue . the first element in pair represents the node and the second element represents vertical level of that node . ; insert root in queue . vertical level of root is 0. ; do vertical order traversal until all the nodes are not visited . ; check if level of node extracted from queue is required level or not . if it is the required level then check if previous value in that level is less than or equal to value of node . ; if left child is not null then push it in queue with level reduced by 1. ; if right child is not null then push it in queue with level increased by 1. ; if the level asked is not present in the given binary tree , that means that level will contain an empty subset . therefore answer will be true . ; 

from collections import deque
from sys import maxsize
INT_MIN = -maxsize


class Node:
    def __init__(self, key):
        self .key = key
        self .left = None
        self .right = None


def isSorted(root: Node, level: int) -> bool:
    if root is None:
        return True
    prevVal = INT_MIN
    currLevel = 0
    currNode = Node(0)
    q = deque()
    q .append((root, 0))
    while q:
        currNode = q[0][0]
        currLevel = q[0][1]
        q .popleft()
        if currLevel == level:
            if prevVal <= currNode .key:
                prevVal = currNode .key
            else:
                return False
        if currNode .left:
            q .append((currNode .left, currLevel - 1))
        if currNode .right:
            q .append((currNode .right, currLevel + 1))
    return True


if __name__ == "__main__":
    root = Node(1)
    root .left = Node(2)
    root .right = Node(5)
    root .left .left = Node(7)
    root .left .right = Node(4)
    root .left .right .left = Node(6)
    level = -1
    if isSorted(root, level):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# minimize operations of removing 2 i | function to find minimum count of steps required to remove all the array elements ; stores minimum count of steps required to remove all the array elements ; update n ; traverse each bit of n ; if current bit is set ; update cntstep ; 
def minimumStepReqArr(arr, N):
    cntStep = 0
    N += 1
    i = 31
    while (i >= 0):
        if (N & (1 << i)):
            cntStep += 1
        i -= 1
    return cntStep


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

# Expected output:
1
# minimize removal of alternating subsequences to empty given binary string | function to find the minimum number of operations required to empty the string ; initialize variables ; traverse the string ; if current character is 0 ; update maximum consecutive 0 s and 1 s ; print the minimum operation ; 
def minOpsToEmptyString(S, N):
    one = 0
    zero = 0
    x0 = 0
    x1 = 0
    for i in range(N):
        if (S[i] == '0'):
            x0 += 1
            x1 = 0
        else:
            x1 += 1
            x0 = 0
        zero = max(x0, zero)
        one = max(x1, one)
    print(max(one, zero))


if __name__ == "__main__":
    S = "0100100111"
    N = len(S)
    minOpsToEmptyString(S, N)

# Expected output:
3
# swap upper and lower triangular halves of a given matrix | function to swap laterally inverted images of upper and lower triangular halves of a given matrix ; store the matrix elements from upper & lower triangular halves ; traverse the matrix mat [ ] [ ] ; find the index ; if current element lies on the principal diagonal ; if current element lies below the principal diagonal ; if current element lies above the principal diagonal ; traverse again to swap values ; find the index ; principal diagonal ; below main diagonal ; above main diagonal ; traverse the matrix and pr ; 
def ReverseSwap(mat, n):
    lowerEle = [[]for i in range(n)]
    upperEle = [[]for i in range(n)]
    index = 0
    for i in range(n):
        for j in range(n):
            index = abs(i - j)
            if (i == j):
                continue
            elif (j < i):
                lowerEle[index].append(mat[i][j])
            else:
                upperEle[index].append(mat[i][j])
    for i in range(n):
        for j in range(n):
            index = abs(i - j)
            if (i == j):
                continue
            elif (j < i):
                mat[i][j] = upperEle[index][-1]
                del upperEle[index][-1]
            else:
                mat[i][j] = lowerEle[index][-1]
                del lowerEle[index][-1]
    for i in range(n):
        for j in range(n):
            print(mat[i][j], end=" ")
        print()


if __name__ == '__main__':
    mat = [[1, 2], [4, 5]]
    N = len(mat)
    ReverseSwap(mat, N)

# Expected output:
1 4 
2 5
# minimize sum of k positive integers with given lcm | function to find the prime power of x ; stores prime powers of x ; iterate over the range [ 2 , sqrt ( x ) ] ; if x is divisible by i ; stores prime power ; calculate prime power of x ; update x ; update p ; insert prime powers into primepow [ ] ; if x exceeds 1 ; function to calculate the sum of array elements ; stores sum of array elements ; traverse the array ; update sum ; function to partition array into k groups such that sum of elements of the k groups is minimum ; if count of prime powers is equal to pos ; stores minimum sum of of each partition of arr [ ] into k groups ; traverse the array arr [ ] ; include primepow [ pos ] into i - th groups ; update res ; remove factors [ pos ] from i - th groups ; utility function to calculate minimum sum of k positive integers whose lcm is x ; stores all prime powers of x ; stores count of prime powers ; stores minimum sum of k positive integers whose lcm is x ; if n is less than or equal to k ; traverse primepow [ ] array ; update sum ; update sum ; arr [ i ] : stores element in i - th group by partitioning the primepow [ ] array ; update sum ; 
def primePower(X):
    primePow = []
    for i in range(2, X + 1):
        if i * i > X + 1:
            break
        if (X % i == 0):
            p = 1
            while (X % i == 0):
                X //= i
                p *= i
            primePow .append(p)
    if (X > 1):
        primePow .append(X)
    return primePow


def getSum(ar):
    sum = 0
    for i in ar:
        sum += i
    return sum


def getMinSum(pos, arr, primePow):
    if (pos == len(primePow)):
        return getSum(arr)
    res = 10 ** 9
    for i in range(len(arr)):
        arr[i] *= primePow[pos]
        res = min(res, getMinSum(pos + 1, arr, primePow))
        arr[i] //= primePow[pos]
    return res


def minimumSumWithGivenLCM(k, x):
    primePow = primePower(x)
    n = len(primePow)
    sum = 0
    if (n <= k):
        for i in primePow:
            sum += i
        sum += k - n
    else:
        arr = [1] * (k)
        sum = getMinSum(0, arr, primePow)
    return sum


if __name__ == '__main__':
    k = 3
    x = 210
    print(minimumSumWithGivenLCM(k, x))

# Expected output:
18
# minimum removal of subsequences of distinct consecutive characters required to empty a given string | function to count minimum operations required to make the string an empty string ; stores count of 1 s by removing consecutive distinct subsequence ; stores count of 0 s by removing consecutive distinct subsequence ; traverse the string ; if current character is 0 ; update cntone ; update cntzero ; if current character is 1 ; update cntzero ; update cntone ; 
def findMinOperationsReqEmpStr(str):
    cntOne = 0
    cntZero = 0
    for element in str:
        if element == '0':
            if cntOne > 0:
                cntOne = cntOne - 1
            cntZero = cntZero + 1
        else:
            if cntZero > 0:
                cntZero = cntZero - 1
            cntOne = cntOne + 1
    return cntOne + cntZero


if __name__ == "__main__":
    str = "0100100111"
    print(findMinOperationsReqEmpStr(str))

# Expected output:
3
# minimum number of flips required such that the last cell of matrix can be reached from any other cell | function to calculate the minimum number of flips required ; dimensions of mat [ ] [ ] ; initialize answer ; count all ' d ' s in the last row ; count all ' r ' s in the last column ; print answer ; 
def countChanges(mat):
    n = len(mat)
    m = len(mat[0])
    ans = 0
    for j in range(m - 1):
        if (mat[n - 1][j] != 'R'):
            ans += 1
    for i in range(n - 1):
        if (mat[i][m - 1] != 'D'):
            ans += 1
    return ans


arr = [['R', 'R', 'R', 'D'], ['D', 'D', 'D', 'R'], ['R', 'D', 'R', 'F']]
cnt = countChanges(arr)
print(cnt)

# Expected output:
2
# smallest subsequence having gcd equal to gcd of given array | python3 program to implement the above approach ; function to print the smallest subsequence that satisfies the condition ; stores gcd of the array . ; traverse the given array ; update gcdarr ; traverse the given array . ; if current element equal to gcd of array . ; generate all possible pairs . ; if gcd of current pair equal to gcdarr ; print current pair of the array ; 

import math


def printSmallSub(arr, N):
    gcdArr = 0
    for i in range(0, N):
        gcdArr = math .gcd(gcdArr, arr[i])
    for i in range(0, N):
        if (arr[i] == gcdArr):
            print(arr[i], end=" ")
            return
        for i in range(0, N):
            for j in range(i + 1, N):
                if (math .gcd(arr[i], arr[j]) == gcdArr):
                    print(arr[i], end=" ")
                    print(arr[j], end=" ")
                    return


if __name__ == "__main__":
    arr = [4, 6, 12]
    N = len(arr)
    printSmallSub(arr, N)

# Expected output:
4 6
# count pairs in an array whose product is composite number | python3 program to implement the above approach ; function to get all the prime numbers in the range [ 1 , x ] ; stores the boolean value to check if a number is prime or not ; mark all non prime numbers as false ; if i is prime number ; mark j as a composite number ; function to get the count of pairs whose product is a composite number ; stores the boolean value to check if a number is prime or not ; stores the count of 1 s ; stores the count of prime numbers ; traverse the given array . ; stores count of pairs whose product is not a composite number ; stores the count of pairs whose product is composite number ; 

X = 1000000


def getPrimeNum():
    isPrime = [True] * (X)
    isPrime[0] = False
    isPrime[1] = False
    i = 2
    while i * i <= X:
        if (isPrime[i]):
            for j in range(i * i, X, i):
                isPrime[j] = False
        i += 1
    return isPrime


def cntPairs(arr, N):
    isPrime = getPrimeNum()
    cntOne = 0
    cntPrime = 0
    for i in range(N):
        if (arr[i] == 1):
            cntOne += 1
        elif (isPrime[i]):
            cntPrime += 1
    cntNonComp = 0
    cntNonComp = (cntPrime * cntOne + cntOne * (cntOne - 1) // 2)
    res = 0
    res = (N * (N - 1) // 2 - cntNonComp)
    return res


if __name__ == "__main__":
    arr = [1, 1, 2, 2, 8]
    N = len(arr)
    print(cntPairs(arr, N))

# Expected output:
5
# find the greater number closest to n having at most one non | python3 program to implement the above approach ; function to calculate x ^ n in log ( n ) ; stores the value of x ^ n ; if n is odd ; function to find the closest number > n having at most 1 non - zero digit ; stores the count of digits in n ; stores the power of 10 ^ ( n - 1 ) ; stores the last ( n - 1 ) digits ; store the answer ; 

import math


def power(X, n):
    res = 1
    while (n != 0):
        if (n & 1 != 0):
            res = res * X
        X = X * X
        n = n >> 1
    return res


def closestgtNum(N):
    n = int(math .log10(N) + 1)
    P = power(10, n - 1)
    Y = N % P
    res = N + (P - Y)
    return res


N = 120
print(closestgtNum(N))

# Expected output:
200
# rearrange an array to make similar indexed elements different from that of another array | function to find the arrangement of array b [ ] such that element at each index of a [ ] and b [ ] are not equal ; length of array ; print not possible , if arrays only have single equal element ; reverse array b ; traverse over arrays to check if there is any index where a [ i ] and b [ i ] are equal ; swap b [ i ] with b [ i - 1 ] ; break the loop ; print required arrangement of array b ; 
def RearrangeB(A, B):
    n = len(A)
    if (n == 1 and A[0] == B[0]):
        print(-1)
        return
    for i in range(n // 2):
        t = B[i]
        B[i] = B[n - i - 1]
        B[n - i - 1] = t
    for i in range(n - 1):
        if (B[i] == A[i]):
            B[i], B[i - 1] = B[i - 1], B[i]
            break
    for k in B:
        print(k, end=" ")


A = [2, 4, 5, 8]
B = [2, 4, 5, 8]
RearrangeB(A, B)

# Expected output:
8 5 4 2
# swap the elements between any two given quadrants of a matrix | python3 program for the above approach ; function to iterate over the x quadrant and swap its element with y quadrant ; iterate over x quadrant ; swap operations ; function to swap the elements of the two given quadrants ; for swapping 1 st and 2 nd quadrant ; for swapping 1 st and 3 rd quadrant ; for swapping 1 st and 4 th quadrant ; for swapping 2 nd and 3 rd quadrant ; for swapping 2 nd and 4 th quadrant ; for swapping 3 rd and 4 th quadrant ; print the resultant matrix ; function to print the matrix ; iterate over the rows ; iterate over the cols ; given matrix ; 

N, M = 6, 6


def swap(mat, startx_X, starty_X, startx_Y, starty_Y):
    row, col = 0, 0
    i = startx_X
    while (bool(True)):
        col = 0
        j = startx_X
        while (bool(True)):
            temp = mat[i][j]
            mat[i][j] = mat[startx_Y + row][starty_Y + col]
            mat[startx_Y + row][starty_Y + col] = temp
            col += 1
            if col >= M // 2:
                break
            j += 1
        row += 1
        if row >= N // 2:
            break
        i += 1


def printMat(mat):
    for i in range(N):
        for j in range(M):
            print(mat[i][j], end=" ")
        print()


def swapQuadOfMatrix(mat, X, Y):
    if (X == 1 and Y == 2):
        swap(mat, 0, 0, 0, M // 2)
    elif (X == 1 and Y == 3):
        swap(mat, 0, 0, N // 2, 0)
    elif (X == 1 and Y == 4):
        swap(mat, 0, 0, N // 2, M // 2)
    elif (X == 2 and Y == 3):
        swap(mat, 0, M // 2, N // 2, 0)
    elif (X == 2 and Y == 4):
        swap(mat, 0, M // 2, N // 2, M // 2)
    elif (X == 3 and Y == 4):
        swap(mat, N // 2, 0, N // 2, M // 2)
    printMat(mat)


mat = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18], [
    19, 20, 21, 22, 23, 24], [25, 26, 27, 28, 29, 30], [31, 32, 33, 34, 35, 36]]
X, Y = 1, 4
swapQuadOfMatrix(mat, X, Y)

# Expected output:
22 23 24 4 5 6 
28 29 30 10 11 12 
34 35 36 16 17 18 
19 20 21 1 2 3 
25 26 27 7 8 9 
31 32 33 13 14 15
# bottom view of a binary tree | tree node class ; constructor of tree node ; method that prints the bottom view . ; initialize a variable ' hd ' with 0 for the root element . ; treemap which stores key value pair sorted on key value ; queue to store tree nodes in level order traversal ; assign initialized horizontal distance value to root node and add it to the queue . ; in stl , append ( ) is used enqueue an item ; loop until the queue is empty ( standard level order loop ) ; in stl , pop ( ) is used dequeue an item ; extract the horizontal distance value from the dequeued tree node . ; put the dequeued tree node to treemap having key as horizontal distance . every time we find a node having same horizontal distance we need to replace the data in the map . ; if the dequeued node has a left child , add it to the queue with a horizontal distance hd - 1. ; if the dequeued node has a right child , add it to the queue with a horizontal distance hd + 1. ; traverse the map elements using the iterator . ; 

class Node:
    def __init__(self, key):
        self .data = key
        self .hd = 1000000
        self .left = None
        self .right = None


def bottomView(root):
    if (root is None):
        return
    hd = 0
    m = dict()
    q = []
    root .hd = hd
    q .append(root)
    while (len(q) != 0):
        temp = q[0]
        q .pop(0)
        hd = temp .hd
        m[hd] = temp .data
        if (temp .left is not None):
            temp .left .hd = hd - 1
            q .append(temp .left)
        if (temp .right is not None):
            temp .right .hd = hd + 1
            q .append(temp .right)
    for i in sorted(m .keys()):
        print(m[i], end=' ')


if __name__ == '__main__':
    root = Node(20)
    root .left = Node(8)
    root .right = Node(22)
    root .left .left = Node(5)
    root .left .right = Node(3)
    root .right .left = Node(4)
    root .right .right = Node(25)
    root .left .right .left = Node(10)
    root .left .right .right = Node(14)
    print("Bottom view of the given binary tree :")
    bottomView(root)

# Expected output:
Bottom view of the given binary tree :
5 10 4 14 25
# minimum increments by index value required to obtain at least two equal array elements | function to calculate the minimum number of steps required ; stores minimum difference ; 
def incrementCount(arr, N):
    mini = arr[0] - arr[1]
    for i in range(2, N):
        mini = min(mini, arr[i - 1] - arr[i])
    print(mini)


N = 3
arr = [12, 8, 4]
incrementCount(arr, N)

# Expected output:
4