giulio98/xlcost-single-prompt huggingface dataset:
# find gcd of each subtree of a given node in an n | maximum number of nodes ; tree represented as adjacency list ; for storing value associates with node ; for storing gcd of every subarray ; number of nodes ; function to find gcd of two numbers . using euclidean algo ; if b == 0 then simply return a ; dfs function to traverse the tree ; initializing answer with gcd of this node . ; iterate over each child of current node ; skipping the parent ; call dfs for each child ; taking gcd of the answer of the child to find node 's gcd ; calling dfs from the root ( 1 ) for precomputing answers ; function to find and prgcd for q queries ; doing preprocessing ; iterate over each given query ; 

N = 10 ** 5 + 5
v = [[]for i in range(N)]
val = [0] * (N)
answer = [0] * (N)
n = 0


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


def DFS(node, parent):
    answer[node] = val[node]
    for child in v[node]:
        if (child == parent):
            continue
        DFS(child, node)
        answer[node] = gcd(answer[node], answer[child])


def preprocess():
    DFS(1, -1)


def findGCD(queries, q):
    preprocess()
    for i in range(q):
        GCD = answer[queries[i]]
        print("For subtree of ", queries[i], ", GCD = ", GCD)


if __name__ == '__main__':
    n = 5
    v[1].append(2)
    v[2].append(1)
    v[1].append(3)
    v[3].append(1)
    v[3].append(4)
    v[4].append(3)
    v[3].append(5)
    v[5].append(3)
    val[1] = 2
    val[2] = 3
    val[3] = 4
    val[4] = 8
    val[5] = 16
    queries = [2, 3, 1]
    q = len(queries)
    findGCD(queries, q)

# Expected output:
For subtree of  2 , GCD =  3
For subtree of  3 , GCD =  4
For subtree of  1 , GCD =  1
# minimize cost to convert given two integers to zero using 
def makeZero(x, y, a, b):
    if (x > y):
        x, y = y, x
    tot_cost = (y - x) * a
    cost1 = 2 * x * a
    cost2 = x * b
    tot_cost += min(cost1, cost2)
    print(tot_cost)


if __name__ == "__main__":
    X, Y = 1, 3
    cost1, cost2 = 391, 555
    makeZero(X, Y, cost1, cost2)

# Expected output:
1337
# find n fractions that sum upto a given fraction n / d | function to split the fraction into the n parts ; loop to find the n - 1 fraction ; loop to print the fractions ; 
def splitFraction(n, d):
    ar = []
    for i in range(0, n):
        ar .append(0)
    first = d + n - 1
    ar[0] = first
    for i in range(1, n):
        temp = first - 1
        ar[i] = first * temp
        first -= 1
    for i in range(0, n):
        if ar[i] % n == 0:
            print("1/", int(ar[i] / n), ",", end=" ")
        else:
            print(n, "/", ar[i], ",", end=" ")


N = 4
D = 2
splitFraction(N, D)

# Expected output:
4 / 5 , 1/ 5 , 1/ 3 , 4 / 6 ,
# count of pairs ( i , j ) in the array such that arr [ i ] is a factor of arr [ j ] | function to return the count of pairs ; 
def numPairs(arr, n):
    ans = 0
    for i in range(n):
        for j in range(i + 1, n):
            if arr[j] % arr[i] == 0:
                ans += 1
    return ans


arr = [1, 1, 2, 2, 3, 3]
n = len(arr)
print(numPairs(arr, n))

# Expected output:
11
# check if array can be converted into strictly decreasing sequence | function to check that array can be converted into a strictly decreasing sequence ; loop to check that each element is greater than the ( n - index ) ; if element is less than ( n - index ) ; if array can be converted ; 
def check(arr, n):
    flag = True
    for i in range(n):
        if (arr[i] < n - i):
            flag = False
    if (flag):
        return True
    else:
        return False


if __name__ == '__main__':
    arr1 = [11, 11, 11, 11]
    n1 = len(arr1)
    if (check(arr1, n1)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# minimize the non | function to minimize the non - zero elements in the given array ; to store the min pos needed ; loop to iterate over the elements of the given array ; if current position a [ i ] is occupied the we can place a [ i ] , a [ i + 1 ] and a [ i + 2 ] elements together at a [ i + 1 ] if exists . ; 
def minOccupiedPosition(A, n):
    minPos = 0
    i = 0
    while i < n:
        if (A[i] > 0):
            minPos += 1
            i += 2
        i += 1
    return minPos


if __name__ == '__main__':
    A = [8, 0, 7, 0, 0, 6]
    n = len(A)
    print(minOccupiedPosition(A, n))

# Expected output:
2
# find minimum number k such that sum of array after multiplication by k exceed s | python3 implementation of the approach ; function to return the minimum value of k that satisfies the given condition ; store sum of array elements ; calculate the sum after ; return minimum possible k ; 

import math


def findMinimumK(a, n, S):
    sum = 0
    for i in range(0, n):
        sum += a[i]
    return math .ceil(((S + 1) * 1.0) / (sum * 1.0))


a = [10, 7, 8, 10, 12, 19]
n = len(a)
s = 200
print(findMinimumK(a, n, s))

# Expected output:
4
# find the largest number smaller than integer n with maximum number of set bits | function to return the largest number less than n ; iterate through all possible values ; multiply the number by 2 i times ; return the final result ; 
def largestNum(n):
    num = 0
    for i in range(32):
        x = (1 << i)
        if ((x - 1) <= n):
            num = (1 << i) - 1
        else:
            break
    return num


if __name__ == "__main__":
    N = 345
    print(largestNum(N))

# Expected output:
255
# find the string having each substring with exactly k distinct characters | function to find the required output string ; each element at index i is modulus of k ; 
def findString(N, K):
    for i in range(N):
        print(chr(ord('A') + i % K), end="")


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

# Expected output:
ABCABCABCA
# find total no of collisions taking place between the balls in which initial direction of each ball is given | function to count no of collision ; length of the string ; 
def count(s):
    cnt, ans = 0, 0
    N = len(s)
    for i in range(N):
        if (s[i] == 'R'):
            cnt += 1
        if (s[i] == 'L'):
            ans += cnt
    return ans


s = "RRLL"
print(count(s))

# Expected output:
4
# maximum number on 7 | function to find the maximum number that can be displayed using the n segments ; condition to check base case ; condition to check if the number is even ; condition to check if the number is odd ; 
def segments(n):
    if (n == 1 or n == 0):
        return
    if (n % 2 == 0):
        print("1", end="")
        segments(n - 2)
    elif (n % 2 == 1):
        print("7", end="")
        segments(n - 3)


if __name__ == "__main__":
    n = 11
    segments(n)

# Expected output:
71111
# minimum number of subsequences required to convert one string to another using greedy algorithm | function to find the minimum number of subsequences required to convert one to another s2 == a and s1 == b ; at least 1 subsequence is required even in best case , when a is same as b ; size of b ; size of a ; create an 2d array next [ ] [ ] of size 26 * sizeofb to store the next occurrence of a character ( ' a ' to ' z ' ) as an index [ 0 , sizeofa - 1 ] ; loop to store the values of index ; if the value of next [ i ] [ j ] is infinite then update it with next [ i ] [ j + 1 ] ; greedy algorithm to obtain the maximum possible subsequence of b to cover the remaining of a using next subsequence ; loop to iterate over the a ; condition to check if the character is not present in the b ; condition to check if there is an element in b matching with character a [ i ] on or next to b [ pos ] given by next [ a [ i ] - ' a ' ] [ pos ] ; condition to check if reached at the end of b or no such element exists on or next to a [ pos ] , thus increment number by one and reinitialise pos to zero ; 
def findMinimumSubsequences(A, B):
    numberOfSubsequences = 1
    sizeOfB = len(B)
    sizeOfA = len(A)
    inf = 1000000
    next = [[inf for i in range(sizeOfB)]for i in range(26)]
    for i in range(sizeOfB):
        next[ord(B[i]) - ord('a')][i] = i
    for i in range(26):
        for j in range(sizeOfB - 2, -1, -1):
            if (next[i][j] == inf):
                next[i][j] = next[i][j + 1]
    pos = 0
    i = 0
    while (i < sizeOfA):
        if (pos == 0 and next[ord(A[i]) - ord('a')][pos] == inf):
            numberOfSubsequences = -1
            break
        elif (pos < sizeOfB and next[ord(A[i]) - ord('a')][pos] < inf):
            nextIndex = next[ord(A[i]) - ord('a')][pos] + 1
            pos = nextIndex
            i += 1
        else:
            numberOfSubsequences += 1
            pos = 0
    return numberOfSubsequences


if __name__ == '__main__':
    A = "aacbe"
    B = "aceab"
    print(findMinimumSubsequences(A, B))

# Expected output:
3
# vertical and horizontal retrieval ( mrt ) on tapes | python3 program to print horizontal filling ; it is used for checking whether tape is full or not ; it is used for calculating total retrieval time ; it is used for calculating mean retrieval time ; vector is used because n number of records can insert in one tape with size constraint ; null vector obtained to use fresh vector 'v ; initialize variables to 0 for each iteration ; sum is used for checking whether i 'th tape is full or not ; check sum less than size of tape ; increment in j for next record ; calculating total retrieval time ; mrt formula ; calculating mean retrieval time using formula ; v . size ( ) is function of vector is used to get size of vector ; 
def horizontalFill(records,  tape, nt):
    sum = 0
    Retrieval_Time = 0
    current = 0
    v = []

    for i in range(nt):
        v.clear()
        Retrieval_Time = 0
        sum = 0
        print("tape", i + 1, ": [ ", end="")
        sum += records[current]
        while (sum <= tape[i]):
            print(records[current], end=" ")
            v.append(records[current])
            current += 1
            sum += records[current]

        print("]", end="")
        for i in range(len(v)):
            Retrieval_Time += v[i] * (len(v) - i)
        Mrt = Retrieval_Time / len(v)
        print("tMRT :", Mrt)


if __name__ == "__main__":

    records = [15, 2, 8, 23, 45, 50, 60, 120]
    tape = [25, 80, 160]
    n = len(records)
    m = len(tape)
    records.sort()
    horizontalFill(records, tape, m)

# Expected output:
tape 1 : [ 2 8 15 ]tMRT : 12.333333333333334
tape 2 : [ 23 45 ]tMRT : 45.5
tape 3 : [ 50 60 ]tMRT : 80.0
# circular convolution using matrix method | python program to compute circular convolution of two arrays ; function to find circular convolution ; finding the maximum size between the two input sequence sizes ; copying elements of x to row_vec and padding zeros if size of x < maxsize ; copying elements of h to col_vec and padding zeros if size of h is less than maxsize ; generating 2d matrix of circularly shifted elements ; computing result by matrix multiplication and printing results ; 

MAX_SIZE = 10


def convolution(x, h, n, m):
    row_vec = [0] * MAX_SIZE
    col_vec = [0] * MAX_SIZE
    out = [0] * MAX_SIZE
    circular_shift_mat = [[0 for i in range(MAX_SIZE)]for j in range(MAX_SIZE)]
    if (n > m):
        maxSize = n
    else:
        maxSize = m
    for i in range(maxSize):
        if (i >= n):
            row_vec[i] = 0
        else:
            row_vec[i] = x[i]
    for i in range(maxSize):
        if (i >= m):
            col_vec[i] = 0
        else:
            col_vec[i] = h[i]
    k = 0
    d = 0
    for i in range(maxSize):
        curIndex = k - d
        for j in range(maxSize):
            circular_shift_mat[j][i] = row_vec[curIndex % maxSize]
            curIndex += 1
        k = maxSize
        d += 1
    for i in range(maxSize):
        for j in range(maxSize):
            out[i] += circular_shift_mat[i][j] * col_vec[j]
        print(out[i], end=" ")


if __name__ == '__main__':
    x = [5, 7, 3, 2]
    n = len(x)
    h = [1, 5]
    m = len(h)
    convolution(x, h, n, m)

# Expected output:
15 32 38 17
# maximize the number of palindromic strings | python3 program for the above approach ; to check if there is any string of odd length ; if there is at least 1 string of odd length . ; if all the strings are of even length . ; count of 0 's in all  the strings ; count of 1 's in  all the strings ; if z is even and o is even then ans will be n . ; otherwise ans will be n - 1. ; 
def max_palindrome(s, n):
    flag = 0
    for i in range(n):
        if (len(s[i]) % 2 != 0):
            flag = 1
    if (flag == 1):
        return n
    z = 0
    o = 0
    for i in range(n):
        for j in range(len(s[i])):
            if (s[i][j] == '0'):
                z += 1
            else:
                o += 1
    if (o % 2 == 0 and z % 2 == 0):
        return n
    else:
        return n - 1


if __name__ == "__main__":
    n = 3
    s = ["1110", "100110", "010101"]
    print(max_palindrome(s, n))

# Expected output:
2
# minimum possible travel cost among n cities | function to return the minimum cost to travel from the first city to the last ; to store the total cost ; start from the first city ; if found any city with cost less than that of the previous boarded bus then change the bus ; calculate the cost to travel from the currently boarded bus till the current city ; update the currently boarded bus ; finally calculate the cost for the last boarding bus till the ( n + 1 ) th city ; 
def minCost(cost, n):
    totalCost = 0
    boardingBus = 0
    for i in range(1, n):
        if (cost[boardingBus] > cost[i]):
            totalCost += ((i - boardingBus) * cost[boardingBus])
            boardingBus = i
    totalCost += ((n - boardingBus) * cost[boardingBus])
    return totalCost


cost = [4, 7, 8, 3, 4]
n = len(cost)
print(minCost(cost, n))

# Expected output:
18
# minimum cells to be flipped to get a 2 * 2 submatrix with equal elements | python 3 implementation of the approach ; function to return the minimum flips required such that the submatrix from mat [ i ] [ j ] to mat [ i + 1 ] [ j + 1 ] contains all equal elements ; function to return the minimum number of slips required such that the matrix contains at least a single submatrix of size 2 * 2 with all equal elements ; to store the result ; for every submatrix of size 2 * 2 ; update the count of flips required for the current submatrix ; 

import sys


def minFlipsSub(mat, i, j):
    cnt0 = 0
    cnt1 = 0
    if (mat[i][j] == '1'):
        cnt1 += 1
    else:
        cnt0 += 1
    if (mat[i][j + 1] == '1'):
        cnt1 += 1
    else:
        cnt0 += 1
    if (mat[i + 1][j] == '1'):
        cnt1 += 1
    else:
        cnt0 += 1
    if (mat[i + 1][j + 1] == '1'):
        cnt1 += 1
    else:
        cnt0 += 1
    return min(cnt0, cnt1)


def minFlips(mat, r, c):
    res = sys .maxsize
    for i in range(r - 1):
        for j in range(c - 1):
            res = min(res, minFlipsSub(mat, i, j))
    return res


if __name__ == '__main__':
    mat = ["0101", "0101", "0101"]
    r = len(mat)
    c = len(mat[0])
    print(minFlips(mat, r, c))

# Expected output:
2
# count set bits in the kth number after segregating even and odd from n natural numbers | function to return the kth element of the odd - even sequence of length n ; finding the index from where the even numbers will be stored ; return the kth element ; function to return the count of set bits in the kth number of the odd even sequence of length n ; required kth number ; return the count of set bits ; 
def findK(n, k):
    if (n % 2 == 0):
        pos = n // 2
    else:
        pos = (n // 2) + 1
    if (k <= pos):
        return (k * 2 - 1)
    else:
        return ((k - pos) * 2)


def countSetBits(n, k):
    kth = findK(n, k)
    return bin(kth).count('1')


if __name__ == "__main__":
    n = 18
    k = 12
    print(countSetBits(n, k))

# Expected output:
2
# minimum cost to convert str1 to str2 with the given operations | function to return the minimum cost to convert str1 to sr2 ; for every character of str1 ; if current character is not equal in both the strings ; if the next character is also different in both the strings then these characters can be swapped ; change the current character ; 
def minCost(str1, str2, n):
    cost = 0
    for i in range(n):
        if (str1[i] != str2[i]):
            if (i < n - 1 and str1[i + 1] != str2[i + 1]):
                swap(str1[i], str1[i + 1])
                cost += 1
            else:
                cost += 1
    return cost


if __name__ == '__main__':
    str1 = "abb"
    str2 = "bba"
    n = len(str1)
    print(minCost(str1, str2, n))

# Expected output:
2
# partition first n natural number into two sets such that their sum is not coprime | function to find the required sets ; impossible case ; sum of first n - 1 natural numbers ; 
def find_set(n):
    if (n <= 2):
        print("-1")
        return
    sum1 = (n * (n - 1)) / 2
    sum2 = n
    print(sum1, " ", sum2)


n = 8
find_set(n)

# Expected output:
28.0   8
# count common elements in two arrays containing multiples of n and m | recursive function to find gcd using euclidean algorithm ; function to find lcm of two numbers using gcd ; 
def gcd(a, b):
    if (a == 0):
        return b
    return gcd(b % a, a)


def lcm(n, m):
    return (n * m) // gcd(n, m)


if __name__ == "__main__":
    n = 2
    m = 3
    k = 5
    print(k // lcm(n, m))

# Expected output:
0
# check whether a subsequence exists with sum equal to k if arr [ i ] > 2 * arr [ i | function to check whether sum of any set of the array element is equal to k or not ; traverse the array from end to start ; if k is greater than arr [ i ] then subtract it from k ; if there is any subsequence whose sum is equal to k ; 
def CheckForSequence(arr, n, k):
    for i in range(n - 1, -1, -1):
        if (k >= arr[i]):
            k -= arr[i]
    if (k != 0):
        return False
    else:
        return True


if __name__ == "__main__":
    A = [1, 3, 7, 15, 31]
    n = len(A)
    if (CheckForSequence(A, n, 18)):
        print(True)
    else:
        print(False)

# Expected output:
True
# maximum possible sub | function to return the maximum sub - array sum after at most x swaps ; to store the required answer ; for all possible intervals ; keep current ans as zero ; to store the integers which are not part of the sub - array currently under consideration ; to store elements which are part of the sub - array currently under consideration ; create two sets ; swap at most x elements ; remove the minimum of the taken elements ; add maximum of the discarded elements ; update the answer ; return the maximized sub - array sum ; 
def SubarraySum(a, n, x):
    ans = -10000
    for i in range(n):

        for j in range(i, n):
            curans = 0
            pq = []
            pq2 = []
            for k in range(n):
                if (k >= i and k <= j):
                    curans += a[k]
                    pq2.append(a[k])

                else:
                    pq.append(a[k])

            pq.sort()
            pq.reverse()
            pq2.sort()

            ans = max(ans, curans)
            for k in range(1, x + 1):
                if (len(pq) == 0 or len(pq2) == 0 or pq2[0] >= pq[0]):
                    break
                curans -= pq2[0]
                pq2.pop(0)
                curans += pq[0]
                pq.pop(0)
                ans = max(ans, curans)
    return ans


a = [5, -1, 2, 3, 4, -2, 5]
x = 2
n = len(a)
print(SubarraySum(a, n, x))

# Expected output:
19
# generate an array of size k which satisfies the given conditions | python3 implementation of the approach ; function to generate and print the required array ; initializing the array ; finding r ( from above approach ) ; if r < 0 ; finding ceiling and floor values ; fill the array with ceiling values ; fill the array with floor values ; add 1 , 2 , 3 , ... with corresponding values ; there is no solution for below cases ; modify a [ 1 ] and a [ k - 1 ] to get the required array ; 

import sys
from math import floor, ceil


def generateArray(n, k):
    array = [0] * k
    remaining = n - int(k * (k + 1) / 2)
    if remaining < 0:
        print("NO")
        sys .exit()
    right_most = remaining % k
    high = ceil(remaining / k)
    low = floor(remaining / k)
    for i in range(k - right_most, k):
        array[i] = high
    for i in range(k - right_most):
        array[i] = low
    for i in range(k):
        array[i] += i + 1
    if k - 1 != remaining or k == 1:
        print(*array)
        sys .exit()
    elif k == 2 or k == 3:
        print("-1")
        sys .exit()
    else:
        array[1] -= 1
        array[k - 1] += 1
        print(*array)
        sys .exit()


if __name__ == "__main__":
    n, k = 26, 6
    generateArray(n, k)

# Expected output:
1 2 4 5 6 8
# maximize the given number by replacing a segment of digits with the alternate digits given | function to return the maximized number ; iterate till the end of the string ; check if it is greater or not ; replace with the alternate till smaller ; return original s in case no change took place ; 
def get_maximum(s, a):
    s = list(s)
    n = len(s)
    for i in range(n):
        if (ord(s[i]) - ord('0') < a[ord(s[i]) - ord('0')]):
            j = i
            while (j < n and (ord(s[j]) - ord('0')
                   <= a[ord(s[j]) - ord('0')])):
                s[j] = chr(ord('0') + a[ord(s[j]) - ord('0')])
                j += 1
            return "".join(s)
    return s


if __name__ == "__main__":
    s = "1337"
    a = [0, 1, 2, 5, 4, 6, 6, 3, 1, 9]
    print(get_maximum(s, a))

# Expected output:
1557
# number of times the largest perfect square number can be subtracted from n | python3 implementation of the approach ; function to return the count of steps ; variable to store the count of steps ; iterate while n > 0 ; get the largest perfect square and subtract it from n ; increment steps ; return the required count ; 

from math import sqrt


def countSteps(n):
    steps = 0
    while (n):
        largest = int(sqrt(n))
        n -= (largest * largest)
        steps += 1
    return steps


if __name__ == "__main__":
    n = 85
    print(countSteps(n))

# Expected output:
2
# maximum array sum that can be obtained after exactly k changes | utility function to return the sum of the array elements ; function to return the maximized sum of the array after performing the given operation exactly k times ; sort the array elements ; change signs of the negative elements starting from the smallest ; if a single operation has to be performed then it must be performed on the smallest positive element ; to store the index of the minimum element ; update the minimum index ; perform remaining operation on the smallest element ; return the sum of the updated array ; 
def sumArr(arr, n):
    sum = 0
    for i in range(n):
        sum += arr[i]
    return sum


def maxSum(arr, n, k):
    arr .sort(reverse=False)
    i = 0
    while (i < n and k > 0 and arr[i] < 0):
        arr[i] *= -1
        k -= 1
        i += 1
    if (k % 2 == 1):
        min = 0
        for i in range(1, n):
            if (arr[min] > arr[i]):
                min = i
        arr[min] *= -1
    return sumArr(arr, n)


if __name__ == '__main__':
    arr = [-5, 4, 1, 3, 2]
    n = len(arr)
    k = 4
    print(maxSum(arr, n, k))

# Expected output:
13