giulio98/xlcost-single-prompt huggingface dataset:
# check if given array can be rearranged such that mean is equal to median | function to return true or false if size of array is odd ; to prevent overflow ; if element is greater than mid , then it can only be present in right subarray ; if element is smaller than mid , then it can only be present in left subarray ; else the element is present at the middle then return 1 ; when element is not present in array then return 0 ; function to return true or false if size of array is even ; calculating candidate median ; if candidate median if greater than mean then decrement j ; if candidate median if less than mean then increment i ; if candidate median if equal to mean then return 1 ; when no candidate found for mean ; function to return true if mean can be equal to any candidate median otherwise return false ; calculating mean ; if n is odd ; if n is even ; 
def binarySearch(arr, size, key):
    low = 0
    high = size - 1
    while (low <= high):
        mid = low + (high - low) // 2
        if (key > arr[mid]):
            low = mid + 1
        elif (key < arr[mid]):
            high = mid - 1
        else:
            return 1
    return 0


def twoPointers(arr, N, mean):
    i = 0
    j = N - 1
    while (i < j):
        temp = (arr[i] + arr[j]) / 2
        if (temp > mean):
            j = j - 1
        elif (temp < mean):
            i = i + 1
        else:
            return 1
    return 0


def checkArray(arr, N):
    sum = 0
    for i in range(0, N):
        sum += arr[i]
    mean = sum / N
    if (N & 1):
        return binarySearch(arr, N, mean)
    else:
        return twoPointers(arr, N, mean)


if __name__ == "__main__":
    arr = [1.0, 3.0, 6.0, 9.0, 12.0, 32.0]
    N = len(arr)
    if (checkArray(arr, N)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# count of distinct integers belonging to first n terms of at least one of given gps | function to find the count of distinct integers that belong to the first n terms of at least one of them is gp ; stores the integers that occur in gps in a set data - structure ; stores the current integer of the first gp ; iterate first n terms of first gp ; insert the ith term of gp in s ; stores the current integer of the second gp ; iterate first n terms of second gp ; return answer ; 
def UniqueGeometricTerms(N, a1, r1, a2, r2):
    S = set()
    p1 = a1
    for i in range(N):
        S .add(p1)
        p1 = (p1 * r1)
    p2 = a2
    for i in range(N):
        S .add(p2)
        p2 = (p2 * r2)
    return len(S)


if __name__ == '__main__':
    N = 5
    a1 = 3
    r1 = 2
    a2 = 2
    r2 = 3
    print(UniqueGeometricTerms(N, a1, r1, a2, r2))

# Expected output:
9
# minimize operations to make all array elements | function to find minimum the number of operations required to make all the array elements to - 1 ; stores the array elements with their corresponding indices ; push the array element and it 's index ; sort the elements according to it 's first value ; stores the minimum number of operations required ; traverse until vp is not empty ; stores the first value of vp ; stores the second value of vp ; update the mincnt ; pop the back element from the vp until the first value is same as val and difference between indices is less than k ; return the mincnt ; 
def minOperations(arr, N, K):
    vp = []
    for i in range(N):
        vp .append([arr[i], i])
    vp .sort()
    minCnt = 0
    while (len(vp) != 0):
        val = vp[-1][0]
        ind = vp[-1][1]
        minCnt += 1
        while (len(vp) != 0 and vp[-1][0] == val and ind - vp[-1][1] + 1 <= K):
            vp .pop()
    return minCnt


if __name__ == "__main__":
    arr = [18, 11, 18, 11, 18]
    K = 3
    N = len(arr)
    print(minOperations(arr, N, K))

# Expected output:
3
# find array sum after incrementing by k adjacent elements of every positive element m times | function to find the nearest non - zero element in the left direction ; stores the index of the first element greater than 0 from the right side ; traverse the array in the range [ 1 , n ] ; check arr [ i ] is greater than 0 ; update the value of l ; traverse the array from the left side ; check arr [ i ] is greater than 0 ; update the value of l ; update the value of steps [ i ] ; function to find the nearest non - zero element in the right direction ; stores the index of the first element greater than 0 from the left side ; traverse the array from the left side ; check arr [ i ] is greater than 0 ; update the value of r ; traverse the array from the right side ; check arr [ i ] is greater than 0 ; update the value of r ; update the value of steps [ i ] ; function to find the sum of the array after the given operation m times ; stores the distance of the nearest non zero element . ; stores sum of the initial array arr [ ] ; traverse the array from the left side ; update the value of sum ; print the total sum of the array ; 
def nearestLeft(arr, N, steps):
    L = -N
    for i in range(N - 1, -1, -1):
        if (arr[i] > 0):
            L = -(N - i)
            break
    for i in range(N):
        if (arr[i] > 0):
            L = i
        steps[i] = i - L


def nearestRight(arr, N, steps):
    R = 2 * N
    for i in range(N):
        if (arr[i] > 0):
            R = N + i
            break
    for i in range(N - 1, -1, -1):
        if (arr[i] > 0):
            R = i
        steps[i] = min(steps[i], R - i)


def findSum(arr, N, M, K):
    steps = [0] * N
    s = sum(arr)
    if (s == 0):
        return 0
    nearestLeft(arr, N, steps)
    nearestRight(arr, N, steps)
    for i in range(N):
        s += 2 * K * max(0, M - steps[i])
    return s


if __name__ == "__main__":
    arr = [0, 1, 0, 1, 0, 0]
    N = len(arr)
    M = 2
    K = 1
    print(findSum(arr, N, M, K))

# Expected output:
16
# smallest vertex in the connected components of all the vertices in given undirect graph | python 3 program for the above approach ; stores the parent and size of the set of the ith element ; function to initialize the ith set ; function to find set of ith vertex ; base case ; recursive call to find set ; function to unite the set that includes a and the set that includes b ; if a and b are not from same set ; function to find the smallest vertex in the connected component of the ith vertex for all i in range [ 1 , n ] ; loop to initialize the ith set ; loop to unite all vertices connected by edges into the same set ; stores the minimum vertex value for ith set ; loop to iterate over all vertices ; if current vertex does not exist in minval initialize it with i ; update the minimum value of the set having the ith vertex ; loop to print required answer ; 

maxn = 100
parent = [0] * maxn
Size = [0] * maxn


def make_set(v):
    parent[v] = v
    Size[v] = 1


def find_set(v):
    if (v == parent[v]):
        return v
    parent[v] = find_set(parent[v])
    return parent[v]


def union_sets(a, b):
    a = find_set(a)
    b = find_set(b)
    if (a != b):
        if (Size[a] < Size[b]):
            a, b = b, a
        parent[b] = a
        Size[a] += Size[b]


def findMinVertex(N, edges):
    for i in range(1, N + 1):
        make_set(i)
    for i in range(len(edges)):
        union_sets(edges[i][0], edges[i][1])
    minVal = {}
    for i in range(1, N + 1):
        if (find_set(i)not in minVal):
            minVal[find_set(i)] = i
        else:
            minVal[find_set(i)] = min(minVal[find_set(i)], i)
    for i in range(1, N + 1):
        print(minVal[find_set(i)], end=" ")


if __name__ == "__main__":
    N = 6
    edges = [[1, 3], [2, 4]]
    findMinVertex(N, edges)

# Expected output:
1 2 1 2 5 6
# count of pairs in given range having their ratio equal to ratio of product of their digits | function to find the product of digits of the given number ; function to find the count of pairs ( a , b ) such that a : b = ( product ofdigits of a ) : ( product of digits of b ) ; stores the count of the valid pairs ; loop to iterate over all unordered pairs ( a , b ) ; stores the product of digits of a ; stores the product of digits of b ; if x != 0 and y != 0 and a : b is equivalent to x : y ; increment valid pair count ; return answer ; 
def getProduct(n):
    product = 1
    while (n != 0):
        product = product * (n % 10)
        n = n // 10
    return product


def countPairs(L, R):
    cntPair = 0
    for a in range(L, R + 1, 1):
        for b in range(a + 1, R + 1, 1):
            x = getProduct(a)
            y = getProduct(b)
            if (x and y and (a * y) == (b * x)):
                cntPair += 1
    return cntPair


if __name__ == '__main__':
    L = 1
    R = 100
    print(countPairs(1, 100))

# Expected output:
43
# maximize matrix sum by flipping the sign of any adjacent pairs | python 3 program for the above approach ; function to find the maximum sum of matrix element after flipping the signs of adjacent matrix elements ; initialize row and column ; stores the sum of absolute matrix element ; find the minimum absolute value in the matrix ; store count of negatives ; find the smallest absolute value in the matrix ; increment the count of negative numbers ; find the absolute sum ; if the count of negatives is even then print the sum ; subtract minimum absolute element ; 

import sys


def maxSum(matrix):
    r = len(matrix)
    c = len(matrix[0])
    sum = 0
    mini = sys .maxsize
    count = 0
    for i in range(r):
        for j in range(c):
            k = matrix[i][j]
            mini = min(mini, abs(k))
            if (k < 0):
                count += 1
            sum += abs(k)
    if (count % 2 == 0):
        return sum
    else:
        return (sum - 2 * mini)


if __name__ == '__main__':
    matrix = [[2, -2], [-2, 2]]
    print(maxSum(matrix))

# Expected output:
8
# find the last positive element remaining after repeated subtractions of smallest positive element from all array elements | function to calculate last positive element of the array ; return the first element if n = 1 ; stores the greatest and the second greatest element ; traverse the array a [ ] ; if current element is greater than the greatest element ; if current element is greater than second greatest element ; return the final answer ; 
def lastPositiveElement(arr):
    N = len(arr)
    if (N == 1):
        return arr[0]
    greatest = -1
    secondGreatest = -1
    for x in arr:
        if (x >= greatest):
            secondGreatest = greatest
            greatest = x
        elif (x >= secondGreatest):
            secondGreatest = x
    return greatest - secondGreatest


if __name__ == "__main__":
    arr = [3, 5, 4, 7]
    print(lastPositiveElement(arr))

# Expected output:
2
# reduce given array by replacing subarrays with values less than k with their sum | function to replace all the subarray having values < k with their sum ; stores the sum of subarray having elements less than k ; stores the updated array ; traverse the array ; update the sum ; otherwise , update the vector ; print the result ; 
def updateArray(arr, K):
    sum = 0
    res = []
    for i in range(0, int(len(arr))):
        if (arr[i] < K):
            sum += arr[i]
        else:
            if (sum != 0):
                res .append(sum)
            sum = 0
            res .append(arr[i])
    if (sum != 0):
        res .append(sum)
    for it in res:
        print(it, end=" ")


if __name__ == "__main__":
    arr = [200, 6, 36, 612, 121, 66, 63, 39, 668, 108]
    K = 100
    updateArray(arr, K)

# Expected output:
200 42 612 121 168 668 108
# minimum size of set having either element in range [ 0 , x ] or an odd power of 2 with sum n | python program for the above approach ; function to find the highest odd power of 2 in the range [ 0 , n ] ; if p is even , subtract 1 ; function to find the minimum operations to make n ; if n is odd and x = 0 , then no valid set exist ; stores the minimum possible size of the valid set ; loop to subtract highest odd power of 2 while x < n , step 2 ; if n > 0 , then increment the value of answer by 1 ; return the resultant size of set ; 

import math


def highestPowerof2(n):
    p = int(math .log(n, 2))
    if p % 2 == 0:
        p -= 1
    return int(pow(2, p))


def minStep(N, X):
    if N % 2 and X == 0:
        return -1
    size = 0
    while X < N:
        N -= highestPowerof2(N)
        size += 1
    if N:
        size += 1
    return size


if __name__ == '__main__':
    N = 11
    X = 2
    print(minStep(N, X))

# Expected output:
3
# check if all the digits of the given number are same | function to check if all the digits in the number n is the same or not ; find the last digit ; find the current last digit ; update the value of n ; if there exists any distinct digit , then return no ; otherwise , return yes ; 
def checkSameDigits(N):
    digit = N % 10
    while (N != 0):
        current_digit = N % 10
        N = N // 10
        if (current_digit != digit):
            return "No"
    return "Yes"


if __name__ == "__main__":
    N = 222
    print(checkSameDigits(N))

# Expected output:
Yes
# find number formed by k times alternatively reducing x and adding y to 0 | function to find the value obtained after alternatively reducing x and adding y to 0 total k number of times ; stores the final result after adding only y to 0 ; stores the final number after reducing only x from 0 ; return the result obtained ; 
def positionAfterKJumps(X, Y, K):
    addY = Y * (K // 2)
    reduceX = -1 * X * (K // 2 + K % 2)
    return addY + reduceX


X = 2
Y = 5
K = 3
print(positionAfterKJumps(X, Y, K))

# Expected output:
1
# maximize the largest number k such that bitwise and of k till n is 0 | function to find maximum value of k which makes bitwise and zero . ; take k = n initially ; start traversing from n - 1 till 0 ; whenever we get and as 0 we stop and return ; 
def findMaxK(N):
    K = N
    i = N - 1
    while (i >= 0):
        K &= i
        if (K == 0):
            return i
        i -= 1
    return 0


if __name__ == '__main__':
    N = 5
    print(findMaxK(N))

# Expected output:
3
# count of unordered pair of indices such that ratio of elements at these indices is same as ratio of indices | function of find the count of unordered pairs ( i , j ) in the array such that arr [ j ] / arr [ i ] = j / i . ; stores the count of valid pairs ; iterating over all possible pairs ; check if the pair is valid ; return answer ; 
def countPairs(arr, n):
    count = 0
    for i in range(n - 1):
        for j in range(i + 1, n):
            if ((arr[j] % arr[i] == 0) and (j + 1) % (i + 1) ==
                    0 and (arr[j] // arr[i] == (j + 1) // (i + 1))):
                count += 1
    return count


if __name__ == "__main__":
    arr = [5, -2, 4, 20, 25, -6]
    n = len(arr)
    print(countPairs(arr, n))

# Expected output:
3
# count of unordered pair of indices such that ratio of elements at these indices is same as ratio of indices | function of find the count of unordered pairs ( i , j ) in the array such that arr [ j ] / arr [ i ] = j / i . ; stores the count of valid pairs ; iterating over all values of x in range [ 1 , n ] . ; iterating over all values of y that are divisible by x in the range [ 1 , n ] . ; check if the pair is valid ; return answer ; 
def countPairs(arr, n):
    count = 0
    for x in range(1, n + 1, 1):
        for y in range(2 * x, n + 1, x):
            if ((arr[y - 1] % arr[x - 1] == 0)
                    and (arr[y - 1] // arr[x - 1] == y // x)):
                count += 1
    return count


if __name__ == '__main__':
    arr = [5, -2, 4, 20, 25, -6]
    n = len(arr)
    print(countPairs(arr, n))

# Expected output:
3
# number of minimum length paths between 1 to n including each node | function to calculate the distances from node 1 to n ; stores the number of edges ; storing the edges in vector ; initialize queue ; bfs from 1 st node using queue ; pop from queue ; traversing the adjacency list ; initialize queue ; bfs from last node ; pop from queue ; traverse the adjacency list ; print the count of minimum distance ; 
def countMinDistance(n, m, edges):
    g = [[]for i in range(10005)]
    for i in range(m):
        a = edges[i][0] - 1
        b = edges[i][1] - 1
        g[a].append(b)
        g[b].append(a)
    queue1 = []
    queue1 .append([0, 0])
    dist = [1e9 for i in range(n)]
    ways1 = [0 for i in range(n)]
    dist[0] = 0
    ways1[0] = 1
    while (len(queue1) > 0):
        up = queue1[0]
        queue1 = queue1[:-1]
        x = up[0]
        dis = up[1]
        if (dis > dist[x]):
            continue
        if (x == n - 1):
            continue
        for y in g[x]:
            if (dist[y] > dis + 1):
                dist[y] = dis + 1
                ways1[y] = ways1[x]
                queue1 .append([y, dis + 1])
            elif (dist[y] == dis + 1):
                ways1[y] += ways1[x]
    queue2 = []
    queue2 .append([n - 1, 0])
    dist1 = [1e9 for i in range(n)]
    ways2 = [0 for i in range(n)]
    dist1[n - 1] = 0
    ways2[n - 1] = 1
    while (len(queue2) > 0):
        up = queue2[0]
        queue2 = queue2[:-1]
        x = up[0]
        dis = up[1]
        if (dis > dist1[x]):
            continue
        if (x == 0):
            continue
        for y in g[x]:
            if (dist1[y] > dis + 1):
                dist1[y] = dis + 1
                ways2[y] = ways2[x]
                queue2 .append([y, dis + 1])
            elif (dist1[y] == 1 + dis):
                ways2[y] += ways2[x]
    ways1[n - 1] = 1
    ways2[n - 1] = 1
    for i in range(n):
        print(ways1[i] * ways2[i], end=" ")


if __name__ == '__main__':
    N = 5
    M = 5
    edges = [[1, 2], [1, 4], [1, 3], [2, 5], [2, 4]]
    countMinDistance(N, M, edges)

# Expected output:
1 1 0 1 1
# count of n | python program for the above approach ; function to find the count of odd and even integers having n bits and k set bits ; find the count of even integers ; find the count of odd integers ; print the total count ; 

import math


def Binary_Num(N, K):
    if N - K - 1 >= 0 and K - 1 >= 0:
        num_even = math .factorial(
            N - 2) / (math .factorial(K - 1) * math .factorial(N - K - 1))
    else:
        num_even = 0
    if K - 2 >= 0:
        num_odd = math .factorial(
            N - 2) / (math .factorial(K - 2) * math .factorial(N - K))
    else:
        num_odd = 0
    print(int(num_even), int(num_odd))


if __name__ == "__main__":
    N = 9
    K = 6
    Binary_Num(N, K)

# Expected output:
21 35
# sum of all subsets of a given size ( = k ) | function to find the sum of all sub - sets of size k ; frequency of each array element in summation equation . ; calculate factorial of n - 1 ; calculate factorial of k - 1 ; calculate factorial of n - k ; calculate sum of array . ; sum of all subsets of size k . ; 
def findSumOfAllSubsets(arr, n, k):
    factorial_N = 1
    factorial_d = 1
    factorial_D = 1
    for i in range(1, n, 1):
        factorial_N *= i
    for i in range(1, k, 1):
        factorial_d *= i
    for i in range(1, n - k + 1, 1):
        factorial_D *= i
    freq = factorial_N // (factorial_d * factorial_D)
    sum = 0
    for i in range(n):
        sum += arr[i]
    sum = sum * freq
    print("Sum of all subsets of size = ", k, " is =>", sum)


if __name__ == '__main__':
    arr = [1, 2, 4, 5]
    n = 4
    k = 2
    findSumOfAllSubsets(arr, n, k)

# Expected output:
Sum of all subsets of size =  2  is => 36
# maximize xor by selecting 3 numbers in range [ 0 , a ] , [ 0 , b ] , and [ 0 , c ] respectively | function to calculate maximum triplet xor form 3 ranges ; initialize a variable to store the answer ; create minimum number that have a set bit at ith position ; check for each number and try to greedily choose the bit if possible if a >= cur then a also have a set bit at ith position ; increment the answer ; subtract this value from a ; check for b ; increment the answer ; subtract this value from b ; check for c ; increment the answer ; subtract this value from c ; if any of the above conditions is not satisfied then there is no way to turn that bit on . ; 
def maximumTripletXOR(A, B, C):
    ans = 0
    for i in range(30, -1, -1):
        cur = 1 << i
        if (A >= cur):
            ans += cur
            A -= cur
        elif (B >= cur):
            ans += cur
            B -= cur
        elif (C >= cur):
            ans += cur
            C -= cur
    return ans


A = 6
B = 2
C = 10
print(maximumTripletXOR(A, B, C))

# Expected output:
15
# count of integers in given range having their last k digits are equal | function to return the count of integers from 1 to x having the last k digits as equal ; stores the total count of integers ; loop to iterate over all possible values of z ; terminate the loop when z > x ; add count of integers with last k digits equal to z ; return count ; function to return the count of integers from l to r having the last k digits as equal ; 
def intCount(X, K):
    ans = 0
    for z in range(0, int(pow(10, K)), int((pow(10, K) - 1) / 9)):
        if (z > X):
            break
        ans += int((X - z) / int(pow(10, K)) + 1)
    return ans


def intCountInRange(L, R, K):
    return (intCount(R, K) - intCount(L - 1, K))


L = 49
R = 101
K = 2
print(intCountInRange(L, R, K))

# Expected output:
6
# count subsequence of length 4 having product of the first three elements equal to the fourth element | function to find the total number of subsequences satisfying the given criteria ; stores the count of quadruplets ; stores the frequency of product of the triplet ; traverse the given array arr [ ] ; consider arr [ i ] as fourth element of subsequences ; generate all possible pairs of the array [ 0 , i - 1 ] ; increment the frequency of the triplet ; return the total count obtained ; 
def countQuadruples(A, N):
    ans = 0
    freq = {}
    for i in range(N):
        if A[i] in freq:
            ans += freq[A[i]]
        else:
            freq[A[i]] = 0
        for j in range(i):
            for k in range(j):
                if A[i] * A[j] * A[k] in freq:
                    freq[A[i] * A[j] * A[k]] += 1
                else:
                    freq[A[i] * A[j] * A[k]] = 1
    return ans


if __name__ == '__main__':
    arr = [10, 2, 2, 7, 40, 160]
    N = len(arr)
    print(countQuadruples(arr, N))

# Expected output:
2
# maximum times x and y can be reduced to near 0 using numbers a or b | helper function to check if we can perform mid number of moves ; remove atleast mid * b from both x and y ; if any value is negative return false . ; calculate remaining values ; if val >= mid then it is possible to perform this much moves ; else return false ; initialize a variable to store the answer ; fix the left and right range ; binary search over the answer ; check for the middle value as the answer ; it is possible to perform this much moves ; maximise the answer ; return answer ; 

MAXN = 10000000


def can(Mid, X, Y, A, B):
    p1 = X - Mid * B
    p2 = Y - Mid * B
    if (p1 < 0 or p2 < 0):
        return False
    k = A - B
    if (k == 0):
        return True
    val = p1 // k + p2 // k
    if (val >= Mid):
        return True
    return False


def maxPossibleMoves(X, Y, A, B):
    ans = 0
    L = 1
    R = MAXN
    while (L <= R):
        Mid = (L + R) // 2
        if (can(Mid, X, Y, A, B)):
            L = Mid + 1
            ans = max(ans, Mid)
        else:
            R = Mid - 1
    return ans


X = 10
Y = 12
A = 2
B = 5
if (A < B):
    tmp = A
    A = B
    B = tmp
print(maxPossibleMoves(X, Y, A, B))

# Expected output:
3
# find two proper factors of n such that their sum is coprime with n | python program for the above approach ; function to find two proper factors of n such that their sum is coprime with n ; find factors in sorted order ; find largest value of d2 such that d1 and d2 are co - prime ; check if d1 and d2 are proper factors of n ; print answer ; no such factors exist ; 

import math


def printFactors(n):
    for i in range(2, int(math .sqrt(n)) + 1):
        if (n % i == 0):
            d1 = i
            d2 = n
            while (d2 % d1 == 0):
                d2 = d2 // d1
            if (d1 > 1 and d2 > 1):
                print(d1, d2, sep=", ")
                return
    print(-1)


N = 10
printFactors(N)

# Expected output:
2, 5