giulio98/xlcost-single-prompt huggingface dataset:
# count of subsets whose product is multiple of unique primes | python program for the above approach ; function to check number has distinct prime ; while n has factors of two ; traversing till sqrt ( n ) ; if n has a factor of i ; while n has a factor of i ; covering case , n is prime ; function to check wheather num can be added to the subset ; recursive function to count subset ; base case ; if currsubset is empty ; if unique [ pos ] can be added to the subset ; function to count the subsets ; initialize unique ; check it is a product of distinct primes ; count frequency of unique element ; function call ; 

from math import gcd, sqrt


def checkDistinctPrime(n):
    original = n
    product = 1
    if (n % 2 == 0):
        product *= 2
        while (n % 2 == 0):
            n = n // 2
    for i in range(3, int(sqrt(n)), 2):
        if (n % i == 0):
            product = product * i
            while (n % i == 0):
                n = n // i
    if (n > 2):
        product = product * n
    return product == original


def check(pos, subset, unique):
    for num in subset:
        if gcd(num, unique[pos]) != 1:
            return False
    return True


def countPrime(pos, currSubset, unique, frequency):
    if pos == len(unique):
        if not currSubset:
            return 0
        count = 1
        for element in currSubset:
            count *= frequency[element]
        return count
    if check(pos, currSubset, unique):
        return countPrime(pos + 1, currSubset, unique, frequency) + countPrime(pos + 1, currSubset + [unique[pos]], unique, frequency)
    else:
        return countPrime(pos + 1, currSubset, unique, frequency)


def countSubsets(arr, N):
    unique = set()
    for element in arr:
        if checkDistinctPrime(element):
            unique .add(element)
    unique = list(unique)
    frequency = dict()
    for element in unique:
        frequency[element] = arr .count(element)
    ans = countPrime(0, [], unique, frequency)
    return ans


if __name__ == "__main__":
    arr = [2, 4, 7, 10]
    N = len(arr)
    ans = countSubsets(arr, N)
    print(ans)

# Expected output:
5
# lexicographically largest possible by merging two strings by adding one character at a time | recursive function for finding the lexicographically largest string ; if either of the string length is 0 , return the other string ; if s1 is lexicographically larger than s2 ; take first character of s1 and call the function ; take first character of s2 and recursively call function for remaining string ; 
def largestMerge(s1, s2):
    if len(s1) == 0 or len(s2) == 0:
        return s1 + s2
    if (s1 > s2):
        return s1[0] + largestMerge(s1[1:], s2)
    return s2[0] + largestMerge(s1, s2[1:])


if __name__ == '__main__':
    s1 = "geeks"
    s2 = "forgeeks"
    print(largestMerge(s1, s2))

# Expected output:
gforgeekseeks
# minimum distance between duplicates in a string | this function is used to find the required the minimum distances of repeating characters ; define dictionary and list ; traverse through string ; if character present in dictionary ; difference between current position and last stored value ; updating current position ; storing difference in list ; if character not in dictionary assign it with initial of its position ; if no element inserted in list i . e . no repeating characters ; return minimum distance ; 
def shortestDistance(S, N):
    dic = {}
    dis = []
    for i in range(N):
        if S[i] in dic:
            var = i - dic[S[i]]
            dic[S[i]] = i
            dis .append(var)
        else:
            dic[S[i]] = i
    if (len(dis) == 0):
        return -1
    else:
        return min(dis) - 1


S = "geeksforgeeks"
N = 13
print(shortestDistance(S, N))

# Expected output:
0
# number of open doors | tcs coding question | python3 code for the above approach ; function that counts the number of doors opens after the nth turn ; find the number of open doors ; return the resultant count of open doors ; 

import math


def countOpenDoors(N):
    doorsOpen = int(math .sqrt(N))
    return doorsOpen


if __name__ == '__main__':
    N = 100
    print(countOpenDoors(N))

# Expected output:
10
# minimum number of candies required to distribute among children based on given conditions | function to count the minimum number of candies that is to be distributed ; stores total count of candies ; stores the amount of candies allocated to a student ; if the value of n is 1 ; traverse the array arr [ ] ; if arr [ i + 1 ] is greater than arr [ i ] and ans [ i + 1 ] is at most ans [ i ] ; assign ans [ i ] + 1 to ans [ i + 1 ] ; iterate until i is atleast 0 ; if arr [ i ] is greater than arr [ i + 1 ] and ans [ i ] is at most ans [ i + 1 ] ; assign ans [ i + 1 ] + 1 to ans [ i ] ; if arr [ i ] is equals arr [ i + 1 ] and ans [ i ] is less than ans [ i + 1 ] ; assign ans [ i + 1 ] + 1 to ans [ i ] ; increment the sum by ans [ i ] ; return the resultant sum ; 
def countCandies(arr, n):
    sum = 0
    ans = [1] * n
    if (n == 1):
        return 1
    for i in range(n - 1):
        if (arr[i + 1] > arr[i] and ans[i + 1] <= ans[i]):
            ans[i + 1] = ans[i] + 1
    for i in range(n - 2, -1, -1):
        if (arr[i] > arr[i + 1] and ans[i] <= ans[i + 1]):
            ans[i] = ans[i + 1] + 1
        elif (arr[i] == arr[i + 1] and ans[i] < ans[i + 1]):
            ans[i] = ans[i + 1] + 1
        sum += ans[i]
    sum += ans[n - 1]
    return sum


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

# Expected output:
5
# maximize profit possible by selling m products such that profit of a product is the number of products left of that supplier | function to find the maximum profit by selling m number of products ; initialize a max - heap to keep track of the maximum value ; stores the maximum profit ; traverse the array and push all the elements in max_heap ; iterate a loop until m > 0 ; decrement the value of m by 1 ; pop the maximum element from the heap ; update the maxprofit ; push ( x - 1 ) to max heap ; print the result ; 
def findMaximumProfit(arr, M, N):
    max_heap = []
    maxProfit = 0
    for i in range(0, N):
        max_heap .append(arr[i])
    max_heap .sort()
    max_heap .reverse()
    while (M > 0):
        M -= 1
        X = max_heap[0]
        max_heap .pop(0)
        maxProfit += X
        max_heap .append(X - 1)
        max_heap .sort()
        max_heap .reverse()
    print(maxProfit)


arr = [4, 6]
M = 4
N = len(arr)
findMaximumProfit(arr, M, N)

# Expected output:
19
# generate an array with k positive numbers such that arr [ i ] is either | python program for the above approach function to generate the resultant sequence of first n natural numbers ; initialize an array of size n ; stores the sum of positive and negative elements ; mark the first n - k elements as negative ; update the value of arr [ i ] ; update the value of sumneg ; mark the remaining k elements as positive ; update the value of arr [ i ] ; update the value of sumpos ; if the sum of the sequence is negative , then pr - 1 ; pr the required sequence ; 
def findSequence(n, k):
    arr = [0] * n
    sumPos = 0
    sumNeg = 0
    for i in range(0, n - k):
        arr[i] = -(i + 1)
        sumNeg += arr[i]
    for i in range(n - k, n):
        arr[i] = i + 1
        sumPos += arr[i]
    if (abs(sumNeg) >= sumPos):
        print(-1)
        return
    for i in range(n):
        print(arr[i], end=" ")


N = 10
K = 6
findSequence(N, K)

# Expected output:
-1 -2 -3 -4 5 6 7 8 9 10
# print the indices for every row of a grid from which escaping from the grid is possible | function to find the row index for every row of a matrix from which one can exit the grid after entering from left ; iterate over the range [ 0 , m - 1 ] ; stores the direction from which a person enters a cell ; row index from which one enters the grid ; column index from which one enters the grid ; iterate until j is atleast n - 1 ; if mat [ i ] [ j ] is equal to 1 ; if entry is from left cell ; decrement i by 1 ; assign ' d ' to dir ; if entry is from upper cell ; decrement j by 1 ; assign ' r ' to dir ; if entry is from right cell ; increment i by 1 ; assign ' u ' to dir ; if entry is from bottom cell ; increment j by 1 ; assign ' l ' to dir ; otherwise , ; if entry is from left cell ; increment i by 1 ; assign ' u ' to dir ; if entry is from upper cell ; increment j by 1 ; assign ' l ' to dir ; if entry is from right cell ; decrement i by 1 ; assign ' d ' to dir ; if entry is from lower cell ; decrement j by 1 ; assign ' r ' to dir ; if i or j is less than 0 or i is equal to m or j is equal to n ; if j is equal to n ; otherwise ; 
def findPath(arr, M, N):
    for row in range(M):
        dir = 'L'
        i = row
        j = 0
        while (j < N):
            if (arr[i][j] == 1):
                if (dir == 'L'):
                    i -= 1
                    dir = 'D'
                elif (dir == 'U'):
                    j -= 1
                    dir = 'R'
                elif (dir == 'R'):
                    i += 1
                    dir = 'U'
                elif (dir == 'D'):
                    j += 1
                    dir = 'L'
            else:
                if (dir == 'L'):
                    i += 1
                    dir = 'U'
                elif (dir == 'U'):
                    j += 1
                    dir = 'L'
                elif (dir == 'R'):
                    i -= 1
                    dir = 'D'
                elif (dir == 'D'):
                    j -= 1
                    dir = 'R'
            if (i < 0 or i == M or j < 0 or j == N):
                break
        if (j == N):
            print(i, end=" ")
        else:
            print(-1, end=" ")


arr = [[1, 1, 0, 1], [1, 1, 0, 0], [1, 0, 0, 0], [1, 1, 0, 1], [0, 1, 0, 1]]
M = len(arr)
N = len(arr[0])
findPath(arr, M, N)

# Expected output:
-1 -1 2 3 -1
# maximize sum of array by repeatedly removing an element from pairs whose concatenation is a multiple of 3 | function to calculate sum of digits of an integer ; function to calculate maximum sum of array after removing pairs whose concatenation is divisible by 3 ; stores the sum of digits of array element ; find the sum of digits ; if i is divisible by 3 ; otherwise , if i modulo 3 is 1 ; otherwise , if i modulo 3 is 2 ; return the resultant sum of array elements ; 
def getSum(n):
    ans = 0
    for i in str(n):
        ans += int(i)
    return ans


def getMax(arr):
    maxRem0 = 0
    rem1 = 0
    rem2 = 0
    for i in arr:
        digitSum = getSum(i)
        if digitSum % 3 == 0:
            maxRem0 = max(maxRem0, i)
        elif digitSum % 3 == 1:
            rem1 += i
        else:
            rem2 += i
    print(maxRem0 + max(rem1, rem2))


arr = [23, 12, 43, 3, 56]
getMax(arr)

# Expected output:
91
# minimum edge reversals to make a root | python3 program to find min edge reversal to make every node reachable from root ; method to dfs in tree and populates disrev values ; visit current node ; looping over all neighbors ; distance of v will be one more than distance of u ; initialize back edge count same as parent node 's count ; if there is a reverse edge from u to i , then only update ; return total reversal in subtree rooted at u ; method prints root and minimum number of edge reversal ; number of nodes are one more than number of edges ; data structure to store directed tree ; disrev stores two values - distance and back edge count from root node ; add 0 weight in direction of u to v ; add 1 weight in reverse direction ; initialize all variables ; dfs populates disrev data structure and store total reverse edge counts ; for ( i = 0 i < v i ++ ) { cout < < i < < " ▁ : ▁ " << disrev [ i ] [ 0 ] << " ▁ " << disrev [ i ] [ 1 ] << endl } ; loop over all nodes to choose minimum edge reversal ; ( reversal in path to i ) + ( reversal in all other tree parts ) ; choose minimum among all values ; print the designated root and total edge reversal made ; 

import sys


def dfs(g, disRev, visit, u):
    visit[u] = True
    totalRev = 0
    for i in range(len(g[u])):
        v = g[u][i][0]
        if (not visit[v]):
            disRev[v][0] = disRev[u][0] + 1
            disRev[v][1] = disRev[u][1]
            if (g[u][i][1]):
                disRev[v][1] = disRev[u][1] + 1
                totalRev += 1
            totalRev += dfs(g, disRev, visit, v)
    return totalRev


def printMinEdgeReverseForRootNode(edges, e):
    V = e + 1
    g = [[]for i in range(V)]
    disRev = [[0, 0]for i in range(V)]
    visit = [False for i in range(V)]
    for i in range(e):
        u = edges[i][0]
        v = edges[i][1]
        g[u].append([v, 0])
        g[v].append([u, 1])
    for i in range(V):
        visit[i] = False
        disRev[i][0] = disRev[i][1] = 0
    root = 0
    totalRev = dfs(g, disRev, visit, root)
    res = sys .maxsize
    for i in range(V):
        edgesToRev = ((totalRev - disRev[i][1]) +
                      (disRev[i][0] - disRev[i][1]))
        if (edgesToRev < res):
            res = edgesToRev
            root = i
    print(root, res)


if __name__ == '__main__':
    edges = [[0, 1], [2, 1], [3, 2], [3, 4], [5, 4], [5, 6], [7, 6]]
    e = len(edges)
    printMinEdgeReverseForRootNode(edges, e)

# Expected output:
3 3
# check if 2 * k + 1 non | function to check if the s can be obtained by ( k + 1 ) non - empty substrings whose concatenation and concatenation of the reverse of these k strings ; stores the size of the string ; if n is less than 2 * k + 1 ; stores the first k characters ; stores the last k characters ; reverse the string ; if both the strings are equal ; 
def checkString(s, k):
    n = len(s)
    if (2 * k + 1 > n):
        print("No")
        return
    a = s[0:k]
    b = s[n - k:n]
    b = b[::-1]
    if (a == b):
        print("Yes")
    else:
        print("No")


if __name__ == '__main__':
    S = "qwqwq"
    K = 1
    checkString(S, K)

# Expected output:
Yes
# minimum number of socks required to picked to have at least k pairs of the same color | function to count the minimum number of socks to be picked ; stores the total count of pairs of socks ; find the total count of pairs ; if k is greater than pairs ; otherwise ; 
def findMin(arr, N, k):
    pairs = 0
    for i in range(N):
        pairs += arr[i] / 2
    if (k > pairs):
        return -1
    else:
        return 2 * k + N - 1


arr = [4, 5, 6]
k = 3
print(findMin(arr, 3, k))

# Expected output:
8
# minimum number of bits required to be flipped such that bitwise or of a and b is equal to c | function to count the number of bit flips required on a and b such that bitwise or of a and b is c ; stores the count of flipped bit ; iterate over the range [ 0 , 32 ] ; check if i - th bit of a is set ; check if i - th bit of b is set or not ; check if i - th bit of c is set or not ; if i - th bit of c is unset ; check if i - th bit of a is set or not ; check if i - th bit of b is set or not ; check if i - th bit of c is set or not ; check if i - th bit of both a and b is set ; return the count of bits flipped ; 
def minimumFlips(A, B, C):
    res = 0
    for i in range(32):
        x, y, z = 0, 0, 0
        if (A & (1 << i)):
            x = 1
        if (B & (1 << i)):
            y = 1
        if (C & (1 << i)):
            z = 1
        if (z == 0):
            if (x):
                res += 1
            if (y):
                res += 1
        if (z == 1):
            if (x == 0 and y == 0):
                res += 1
    return res


if __name__ == '__main__':
    A, B, C = 2, 6, 5
    print(minimumFlips(A, B, C))

# Expected output:
3
# queries to calculate bitwise and of an array with updates | store the number of set bits at each position ; function to precompute the prefix count array ; iterate over the range [ 0 , 31 ] ; set the bit at position i if arr [ 0 ] is set at position i ; traverse the array and take prefix sum ; update prefixcount [ i ] [ j ] ; function to find the bitwise and of all array elements ; stores the required result ; iterate over the range [ 0 , 31 ] ; stores the number of set bits at position i ; if temp is n , then set ith position in the result ; print the result ; function to update the prefix count array in each query ; iterate through all the bits of the current number ; store the bit at position i in the current value and the new value ; if bit2 is set and bit1 is unset , then increase the set bits at position i by 1 ; if bit1 is set and bit2 is unset , then decrease the set bits at position i by 1 ; function to find the bitwise and of the array after each query ; fill the prefix count array ; traverse the queries ; store the index and the new value ; store the current element at the index ; update the array element ; apply the changes to the prefix count array ; print the bitwise and of the modified array ; 

prefixCount = [[0 for x in range(32)]for y in range(10000)]


def findPrefixCount(arr, size):
    for i in range(32):
        prefixCount[i][0] = ((arr[0] >> i) & 1)
        for j in range(1, size):
            prefixCount[i][j] = ((arr[j] >> i) & 1)
            prefixCount[i][j] += prefixCount[i][j - 1]


def arrayBitwiseAND(size):
    result = 0
    for i in range(32):
        temp = prefixCount[i][size - 1]
        if (temp == size):
            result = (result | (1 << i))
    print(result, end=" ")


def applyQuery(currentVal, newVal, size):
    for i in range(32):
        bit1 = ((currentVal >> i) & 1)
        bit2 = ((newVal >> i) & 1)
        if (bit2 > 0 and bit1 == 0):
            prefixCount[i][size - 1] += 1
        elif (bit1 > 0 and bit2 == 0):
            prefixCount[i][size - 1] -= 1


def findbitwiseAND(queries, arr, N, M):
    findPrefixCount(arr, N)
    for i in range(M):
        id = queries[i][0]
        newVal = queries[i][1]
        currentVal = arr[id]
        arr[id] = newVal
        applyQuery(currentVal, newVal, N)
        arrayBitwiseAND(N)


if __name__ == "__main__":
    arr = [1, 2, 3, 4, 5]
    queries = [[0, 2], [3, 3], [4, 2]]
    N = len(arr)
    M = len(queries)
    findbitwiseAND(queries, arr, N, M)

# Expected output:
0 0 2
# Find the winner of a game of donating i candies in every i | Function to find the winning player in a game of donating i candies to opponent in i - th move ; Steps in which number of candies of player A finishes ; Steps in which number of candies of player B finishes ; If A 's candies finishes first ; Otherwise ; Candies possessed by player A ; Candies possessed by player B
def stepscount(a, b):
    chance_A = 2 * a - 1
    chance_B = 2 * b
    if (chance_A < chance_B):
        return 'B'
    else:
        return "A"


A = 2
B = 3
print(stepscount(A, B))

# Expected output:
B
# check if a point is inside , outside or on a hyperbola | python3 program for the above approach ; function to check if the point ( x , y ) lies inside , on or outside the given hyperbola ; stores the value of the equation ; generate output based on value of p ; 

from math import pow


def checkpoint(h, k, x, y, a, b):
    p = ((pow((x - h), 2) // pow(a, 2)) - (pow((y - k), 2) // pow(b, 2)))
    if (p > 1):
        print("Outside")
    elif (p == 1):
        print("On the Hyperbola")
    else:
        print("Inside")


if __name__ == "__main__":
    h = 0
    k = 0
    x = 2
    y = 1
    a = 4
    b = 5
    checkpoint(h, k, x, y, a, b)

# Expected output:
Inside
# count subarrays having even bitwise xor | function to count the number of subarrays having even bitwise xor ; store the required result ; generate subarrays with arr [ i ] as the first element ; store xor of current subarray ; generate subarrays with arr [ j ] as the last element ; calculate bitwise xor of the current subarray ; if xor is even , increase ans by 1 ; prthe result ; 
def evenXorSubarray(arr, n):
    ans = 0
    for i in range(n):
        XOR = 0
        for j in range(i, n):
            XOR = XOR ^ arr[j]
            if ((XOR & 1) == 0):
                ans += 1
    print(ans)


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

# Expected output:
4
# modify a binary string by flipping characters such that any pair of indices consisting of 1 s are neither co | function to modify a string such that there doesn 't exist any pair of indices consisting of 1s, whose gcd is 1 and are divisible by each other ; flips characters at indices 4 n , 4 n - 2 , 4 n - 4 . ... upto n terms ; print the string ; 
def findString(S, N):
    strLen = 4 * N
    for i in range(1, N + 1):
        S[strLen - 1] = '1'
        strLen -= 2
    for i in range(4 * N):
        print(S[i], end="")


N = 2
S = [0] * (4 * N)
for i in range(4 * N):
    S[i] = '0'
findString(S, N)

# Expected output:
00000101
# check if a string can be split into two substrings with equal number of vowels | function to check if any character is a vowel or not ; lowercase vowels ; uppercase vowels ; otherwise ; function to check if string s can be split into two substrings with equal number of vowels ; stores the count of vowels in the string s ; traverse over the string ; if s [ i ] is vowel ; stores the count of vowels upto the current index ; traverse over the string ; if s [ i ] is vowel ; if vowelstillnow and totalvowels are equal ; otherwise ; 
def isVowel(ch):
    if (ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u'):
        return True
    if (ch == 'A' or ch == 'E' or ch == 'I' or ch == 'O' or ch == 'U'):
        return True
    return False


def containsEqualStrings(S):
    totalVowels = 0
    for i in range(len(S)):
        if (isVowel(S[i])):
            totalVowels += 1
    vowelsTillNow = 0
    for i in range(len(S)):
        if (isVowel(S[i])):
            vowelsTillNow += 1
            totalVowels -= 1
            if (vowelsTillNow == totalVowels):
                return "Yes"
    return "No"


if __name__ == "__main__":
    S = "geeks"
    print(containsEqualStrings(S))

# Expected output:
Yes
# maximize matrix sum by repeatedly multiplying pairs of adjacent elements with | python3 program to implement the above approach ; function to calculate maximum sum possible of a matrix by multiplying pairs of adjacent elements with - 1 any number of times ( possibly zero ) ; store the maximum sum of matrix possible ; stores the count of negative values in the matrix ; store minimum absolute value present in the matrix ; traverse the matrix row - wise ; update sum ; if current element is negative , increment the negative count ; if current value is less than the overall minimum in a [ ] , update the overall minimum ; if there are odd number of negative values , then the answer will be sum of the absolute values of all elements - 2 * minval ; print maximum sum ; 

import sys


def getMaxSum(A, M, N):
    sum = 0
    negative = 0
    minVal = sys .maxsize
    for i in range(M):
        for j in range(N):
            sum += abs(A[i][j])
            if (A[i][j] < 0):
                negative += 1
            minVal = min(minVal, abs(A[i][j]))
    if (negative % 2):
        sum -= 2 * minVal
    print(sum)


if __name__ == '__main__':
    A = [[4, -8, 6], [3, 7, 2]]
    M = len(A)
    N = len(A[0])
    getMaxSum(A, M, N)

# Expected output:
26
# calculate total wall area of houses painted | function to find the total area of walls painted in n row - houses ; stores total area of n row - houses that needs to be painted ; traverse the array of wall heights ; update total area painted ; update total ; traverse all the houses and print the shared walls ; update total ; print total area needs to paint ; 
def areaToPaint(N, W, L, Heights):
    total = 0
    for i in range(N):
        total += 2 * Heights[i] * W
    total += L * (Heights[0] + Heights[N - 1])
    for i in range(1, N):
        total += L * abs(Heights[i] - Heights[i - 1])
    print(total)


if __name__ == "__main__":
    N = 7
    W = 1
    L = 1
    Heights = [4, 3, 1, 2, 3, 4, 2]
    areaToPaint(N, W, L, Heights)

# Expected output:
52