giulio98/xlcost-single-prompt huggingface dataset:
# k | function to find the kth digit from last in an eger n ; if k is less than equal to 0 ; divide the number n by 10 upto k - 1 times ; if the number n is equal 0 ; pr the right most digit ; 
def kthDigitFromLast(n, k):
    if (k <= 0):
        print("-1")
        return
    while ((k - 1) > 0 and n > 0):
        n = n / 10
        k -= 1
    if (n == 0):
        print("-1")
    else:
        print(int(n % 10))


if __name__ == '__main__':
    n = 2354
    k = 2
    kthDigitFromLast(n, k)

# Expected output:
5
# edit distance | dp | a space efficient dynamic programming based python3 program to find minimum number operations to convert str1 to str2 ; create a dp array to memoize result of previous computations ; base condition when second string is empty then we remove all characters ; start filling the dp this loop run for every character in second string ; this loop compares the char from second string with first string characters ; if first string is empty then we have to perform add character operation to get second string ; if character from both string is same then we do not perform any operation . here i % 2 is for bound the row number . ; if character from both string is not same then we take the minimum from three specified operation ; after complete fill the dp array if the len2 is even then we end up in the 0 th row else we end up in the 1 th row so we take len2 % 2 to get row ; 
def EditDistDP(str1, str2):
    len1 = len(str1)
    len2 = len(str2)
    DP = [[0 for i in range(len1 + 1)]for j in range(2)]
    for i in range(0, len1 + 1):
        DP[0][i] = i
    for i in range(1, len2 + 1):
        for j in range(0, len1 + 1):
            if (j == 0):
                DP[i % 2][j] = i
            elif (str1[j - 1] == str2[i - 1]):
                DP[i % 2][j] = DP[(i - 1) % 2][j - 1]
            else:
                DP[i %
                   2][j] = (1 + min(DP[(i - 1) %
                                       2][j], min(DP[i %
                                                     2][j - 1], DP[(i - 1) %
                                                                   2][j - 1])))
    print(DP[len2 % 2][len1], "")


if __name__ == '__main__':
    str1 = "food"
    str2 = "money"
    EditDistDP(str1, str2)

# Expected output:
4
# sum of bitwise xor of elements of an array with all elements of another array | function to calculate sum of bitwise xor of elements of arr [ ] with k ; initialize sum to be zero ; iterate over each set bit ; stores contribution of i - th bet to the sum ; if the i - th bit is set ; stores count of elements whose i - th bit is not set ; update value ; update value ; add value to sum ; move to the next power of two ; stores the count of elements whose i - th bit is set ; traverse the array ; iterate over each bit ; if the i - th bit is set ; increase count ; 
def xorSumOfArray(arr, n, k, count):
    sum = 0
    p = 1
    for i in range(31):
        val = 0
        if ((k & (1 << i)) != 0):
            not_set = n - count[i]
            val = ((not_set) * p)
        else:
            val = (count[i] * p)
        sum += val
        p = (p * 2)
    return sum


def sumOfXors(arr, n, queries, q):
    count = [0 for i in range(32)]
    for i in range(n):
        for j in range(31):
            if (arr[i] & (1 << j)):
                count[j] += 1
    for i in range(q):
        k = queries[i]
        print(xorSumOfArray(arr, n, k, count), end=" ")


if __name__ == '__main__':
    arr = [5, 2, 3]
    queries = [3, 8, 7]
    n = len(arr)
    q = len(queries)
    sumOfXors(arr, n, queries, q)

# Expected output:
7 34 11
# minimum time required to schedule k processes | function to execute k processes that can be gained in minimum amount of time ; stores all the array elements ; push all the elements to the priority queue ; stores the required result ; loop while the queue is not empty and k is positive ; store the top element from the pq ; add it to the answer ; divide it by 2 and push it back to the pq ; print the answer ; 
def executeProcesses(A, N, K):
    pq = []
    for i in range(N):
        pq .append(A[i])
    ans = 0
    pq .sort()
    while (len(pq) > 0 and K > 0):
        top = pq .pop()
        ans += 1
        K -= top
        top //= 2
        pq .append(top)
        pq .sort()
    print(ans)


A = [3, 1, 7, 4, 2]
K = 15
N = len(A)
executeProcesses(A, N, K)

# Expected output:
4
# count number of pairs ( i , j ) up to n that can be made equal on multiplying with a pair from the range [ 1 , n / 2 ] | function to compute totient of all numbers smaller than or equal to n ; iterate over the range [ 2 , n ] ; if phi [ p ] is not computed already then p is prime ; phi of a prime number p is ( p - 1 ) ; update phi values of all multiples of p ; add contribution of p to its multiple i by multiplying with ( 1 - 1 / p ) ; function to count the pairs ( i , j ) from the range [ 1 , n ] , satisfying the given condition ; stores the counts of first and second type of pairs respectively ; count of first type of pairs ; stores the phi or totient values ; calculate the phi values ; iterate over the range [ n / 2 + 1 , n ] ; update the value of cnt_type2 ; print the total count ; 
def computeTotient(N, phi):
    for p in range(2, N + 1):
        if phi[p] == p:
            phi[p] = p - 1
            for i in range(2 * p, N + 1, p):
                phi[i] = (phi[i] // p) * (p - 1)


def countPairs(N):
    cnt_type1 = 0
    cnt_type2 = 0
    half_N = N // 2
    cnt_type1 = (half_N * (half_N - 1)) // 2
    phi = [0 for i in range(N + 1)]
    for i in range(1, N + 1):
        phi[i] = i
    computeTotient(N, phi)
    for i in range((N // 2) + 1, N + 1):
        cnt_type2 += (i - phi[i] - 1)
    print(cnt_type1 + cnt_type2)


if __name__ == '__main__':
    N = 6
    countPairs(N)

# Expected output:
7
# sum of subsets nearest to k possible from two given arrays | stores the sum closest to k ; stores the minimum absolute difference ; function to choose the elements from the array b [ ] ; if absolute difference is less then minimum value ; update the minimum value ; update the value of ans ; if absolute difference between curr and k is equal to minimum ; update the value of ans ; if i is greater than m - 1 ; includes the element b [ i ] once ; includes the element b [ i ] twice ; excludes the element b [ i ] ; function to find a subset sum whose sum is closest to k ; traverse the array a [ ] ; function call ; return the ans ; 

ans = 10 ** 8
mini = 10 ** 8


def findClosestTarget(i, curr, B, M, K):
    global ans, mini
    if (abs(curr - K) < mini):
        mini = abs(curr - K)
        ans = curr
    if (abs(curr - K) == mini):
        ans = min(ans, curr)
    if (i >= M):
        return
    findClosestTarget(i + 1, curr + B[i], B, M, K)
    findClosestTarget(i + 1, curr + 2 * B[i], B, M, K)
    findClosestTarget(i + 1, curr, B, M, K)


def findClosest(A, B, N, M, K):
    for i in range(N):
        findClosestTarget(0, A[i], B, M, K)
    return ans


if __name__ == '__main__':
    A = [2, 3]
    B = [4, 5, 30]
    N = len(A)
    M = len(B)
    K = 18
    print(findClosest(A, B, N, M, K))

# Expected output:
17
# check if every node can me made accessible from a node of a tree by at most n / 2 given operations |  ; store the indegree of every node ; store the nodes having indegree equal to 0 ; traverse the array ; if the indegree of i - th node is 0 ; increment count0 by 1 ; if the number of operations needed is at most floor ( n / 2 ) ; otherwise ; 
def findNode(mp, n):
    a = [0] * n
    for i in range(n):
        a[i] = mp[i + 1]
    count0 = 0
    for i in range(n):
        if (a[i] == 0):
            count0 += 1
    count0 -= 1
    if (count0 <= (n) / (2)):
        return True
    else:
        return False


if __name__ == "__main__":
    N = 3
    mp = {}
    mp[1] = 0
    mp[2] = 2
    mp[3] = 0
    if (findNode(mp, N)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# check if bitwise and of concatenation of diagonals exceeds that of middle row / column elements of a binary matrix | functio to convert obtained binary representation to decimal value ; stores the resultant number ; traverse string arr ; return the number formed ; function to count the number of set bits in the number num ; stores the count of set bits ; iterate until num > 0 ; function to check if the given matrix satisfies the given condition or not ; to get p , s , mr , and mc ; stores decimal equivalents of binary representations ; gett the number of set bits ; print the answer ; 
def convert(arr):
    ans = 0
    for i in arr:
        ans = (ans << 1) | i
    return ans


def count(num):
    ans = 0
    while num:
        ans += num & 1
        num >>= 1
    return ans


def checkGoodMatrix(mat):
    P = []
    S = []
    MR = []
    MC = []
    for i in range(len(mat)):
        for j in range(len(mat[0])):
            if i == j:
                P .append(mat[i][j])
            if i + j == len(mat) - 1:
                S .append(mat[i][j])
            if i == (len(mat) - 1) // 2:
                MR .append(mat[i][j])
            if j == (len(mat) - 1) // 2:
                MC .append(mat[i][j])
    S .reverse()
    P = convert(P)
    S = convert(S)
    MR = convert(MR)
    MC = convert(MC)
    setBitsPS = count(P & S)
    setBitsMM = count(MR & MC)
    if setBitsPS > setBitsMM:
        print("Yes")
    else:
        print("No")


mat = [[1, 0, 1], [0, 0, 1], [0, 1, 1]]
checkGoodMatrix(mat)

# Expected output:
No
# construct a tree whose sum of nodes of all the root to leaf path is not divisible by the count of nodes in that path | python3 program for the above approach ; function to assign values to nodes of the tree s . t . sum of values of nodes of path between any 2 nodes is not divisible by length of path ; stores the adjacency list ; create a adjacency list ; stores whether any node is visited or not ; stores the node values ; variable used to assign values to the nodes alternatively to the parent child ; declare a queue ; push the 1 st node ; assign k value to this node ; dequeue the node ; mark it as visited ; upgrade the value of k ; assign k to the child nodes ; if the child is unvisited ; enqueue the child ; assign k to the child ; print the value assigned to the nodes ; 

from collections import deque


def assignValues(Edges, n):
    tree = [[]for i in range(n + 1)]
    for i in range(n - 1):
        u = Edges[i][0]
        v = Edges[i][1]
        tree[u].append(v)
        tree[v].append(u)
    visited = [False] * (n + 1)
    answer = [0] * (n + 1)
    K = 1
    q = deque()
    q .append(1)
    answer[1] = K
    while (len(q) > 0):
        node = q .popleft()
        visited[node] = True
        K = 2 if (answer[node] == 1)else 1
        for child in tree[node]:
            if (not visited[child]):
                q .append(child)
                answer[child] = K
    for i in range(1, n + 1):
        print(answer[i], end=" ")


if __name__ == '__main__':
    N = 7
    Edges = [[1, 2], [4, 6], [3, 5], [1, 4], [7, 5], [5, 1]]
    assignValues(Edges, N)

# Expected output:
1 2 1 2 2 1 1
# number of full binary trees such that each node is product of its children | return the number of all possible full binary tree with given product property . ; finding the minimum and maximum values in given array . ; marking the presence of each array element and initialising the number of possible full binary tree for each integer equal to 1 because single node will also contribute as a full binary tree . ; from minimum value to maximum value of array finding the number of all possible full binary trees . ; find if value present in the array ; for each multiple of i , less than equal to maximum value of array ; if multiple is not present in the array then continue . ; finding the number of possible full binary trees for multiple j by multiplying number of possible full binary tree from the number i and number of possible full binary tree from i / j . ; condition for possiblity when left chid became right child and vice versa . ; 
def numoffbt(arr, n):
    maxvalue = -2147483647
    minvalue = 2147483647
    for i in range(n):
        maxvalue = max(maxvalue, arr[i])
        minvalue = min(minvalue, arr[i])
    mark = [0 for i in range(maxvalue + 2)]
    value = [0 for i in range(maxvalue + 2)]
    for i in range(n):
        mark[arr[i]] = 1
        value[arr[i]] = 1
    ans = 0
    for i in range(minvalue, maxvalue + 1):
        if (mark[i] != 0):
            j = i + i
            while (j <= maxvalue and j // i <= i):
                if (mark[j] == 0):
                    continue
                value[j] = value[j] + (value[i] * value[j // i])
                if (i != j // i):
                    value[j] = value[j] + (value[i] * value[j // i])
                j += i
        ans += value[i]
    return ans


arr = [2, 3, 4, 6]
n = len(arr)
print(numoffbt(arr, n))

# Expected output:
7
# minimum prime numbers required to be subtracted to make all array elements equal | python3 program for the above approach ; stores the sieve of prime numbers ; function that performs the sieve of eratosthenes ; iterate over the range [ 2 , 1000 ] ; if the current element is a prime number ; mark all its multiples as false ; function to find the minimum number of subtraction of primes numbers required to make all array elements the same ; perform sieve of eratosthenes ; find the minimum value ; stores the value to each array element should be reduced ; if an element exists with value ( m + 1 ) ; stores the minimum count of subtraction of prime numbers ; traverse the array ; if d is equal to 0 ; if d is a prime number ; increase count by 1 ; if d is an even number ; increase count by 2 ; if d - 2 is prime ; increase count by 2 ; otherwise , increase count by 3 ; 

import sys
limit = 100000
prime = [True] * (limit + 1)


def sieve():
    p = 2
    while (p * p <= limit):
        if (prime[p]):
            for i in range(p * p, limit, p):
                prime[i] = False
        p += 1


def findOperations(arr, n):
    sieve()
    minm = sys .maxsize
    for i in range(n):
        minm = min(minm, arr[i])
    val = minm
    for i in range(n):
        if (arr[i] == minm + 1):
            val = minm - 2
            break
    cnt = 0
    for i in range(n):
        D = arr[i] - val
        if (D == 0):
            continue
        elif (prime[D]):
            cnt += 1
        elif (D % 2 == 0):
            cnt += 2
        else:
            if (prime[D - 2]):
                cnt += 2
            else:
                cnt += 3
    return cnt


arr = [7, 10, 4, 5]
N = 4
print(findOperations(arr, N))

# Expected output:
5
# print all unique digits present in concatenation of all array elements in the order of their occurrence | function to print unique elements ; reverse the list ; traverse the list ; function which check for all unique digits ; stores the final number ; stores the count of unique digits ; converting string to integer to remove leading zeros ; stores count of digits ; iterate over the digits of n ; retrieve the last digit of n ; increase the count of the last digit ; remove the last digit of n ; converting string to integer again ; iterate over the digits of n ; retrieve the last digit of n ; if the value of this digit is not visited ; if its frequency is 1 ( unique ) ; mark the digit visited ; remove the last digit of n ; passing this list to print the reversed list ; function to concatenate array elements ; stores the concatenated number ; traverse the array ; convert to equivalent string ; concatenate the string ; passing string to checkunique function ; 
def printUnique(lis):
    lis .reverse()
    for i in lis:
        print(i, end=" ")


def checkUnique(string):
    lis = []
    res = 0
    N = int(string)
    cnt = [0] * 10
    while (N > 0):
        rem = N % 10
        cnt[rem] += 1
        N = N // 10
    N = int(string)
    while (N > 0):
        rem = N % 10
        if (cnt[rem] != 'visited'):
            if (cnt[rem] == 1):
                lis .append(rem)
        cnt[rem] = 'visited'
        N = N // 10
    printUnique(lis)


def combineArray(lis):
    string = ""
    for el in lis:
        el = str(el)
        string = string + el
    checkUnique(string)


arr = [122, 474, 612, 932]
combineArray(arr)

# Expected output:
7 6 9 3
# maximize sum of bitwise and of same | function to calculate sum of bitwise and of same indexed elements of the arrays p [ ] and arr [ ] ; stores the resultant sum ; traverse the array ; update sum of bitwise and ; return the value obtained ; function to generate all permutations and calculate the maximum sum of bitwise and of same indexed elements present in any permutation and an array arr [ ] ; if the size of the array is n ; calculate cost of permutation ; generate all permutations ; update chosen [ i ] ; update the permutation p [ ] ; generate remaining permutations ; return the resultant sum ; function to find the maximum sum of bitwise and of same indexed elements in a permutation of first n natural numbers and arr [ ] ; stores the resultant maximum sum ; stores the generated permutation p ; function call to store result ; print the result ; 
def calcScore(p, arr):
    ans = 0
    for i in range(len(arr)):
        ans += (p[i] & arr[i])
    return ans


def getMaxUtil(p, arr, ans, chosen, N):
    if len(p) == N:
        ans = max(ans, calcScore(p, arr))
        return ans
    for i in range(N):
        if chosen[i]:
            continue
        chosen[i] = True
        p .append(i)
        ans = getMaxUtil(p, arr, ans, chosen, N)
        chosen[i] = False
        p .pop()
    return ans


def getMax(arr, N):
    ans = 0
    chosen = [False for i in range(N)]
    p = []
    res = getMaxUtil(p, arr, ans, chosen, N)
    print(res)


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

# Expected output:
5
# sum of array elements whose count of set bits are unique | function to count the number of set bits in an integer n ; stores the count of set bits ; iterate until n is non - zero ; stores the resultant count ; function to calculate sum of all array elements whose count of set bits are unique ; stores frequency of all possible count of set bits ; stores the sum of array elements ; traverse the array ; count the number of set bits ; traverse the array and update the value of ans ; if frequency is 1 ; 
def setBitCount(n):
    ans = 0
    while n:
        ans += n & 1
        n >>= 1
    return ans


def getSum(arr):
    mp = {}
    ans = 0
    for i in arr:
        key = setBitCount(i)
        mp[key] = [0, i]
    for i in arr:
        key = setBitCount(i)
        mp[key][0] += 1
    for i in mp:
        if mp[i][0] == 1:
            ans += mp[i][1]
    print(ans)


arr = [8, 3, 7, 5, 3]
getSum(arr)

# Expected output:
15
# print indices of pair of array elements required to be removed to split array into 3 equal sum subarrays | function to check if array can be split into three equal sum subarrays by removing a pair ; stores prefix sum array ; traverse the array ; stores sums of all three subarrays ; sum of left subarray ; sum of middle subarray ; sum of right subarray ; check if sum of subarrays are equal ; prthe possible pair ; if no such pair exists , pr - 1 ; 
def findSplit(arr, N):
    sum = [i for i in arr]
    for i in range(1, N):
        sum[i] += sum[i - 1]
    for l in range(1, N - 3):
        for r in range(l + 2, N - 1):
            lsum, rsum, msum = 0, 0, 0
            lsum = sum[l - 1]
            msum = sum[r - 1] - sum[l]
            rsum = sum[N - 1] - sum[r]
            if (lsum == rsum and rsum == msum):
                print(l, r)
                return
    print(-1)


if __name__ == '__main__':
    arr = [2, 5, 12, 7, 19, 4, 3]
    N = len(arr)
    findSplit(arr, N)

# Expected output:
2 4
# print indices of pair of array elements required to be removed to split array into 3 equal sum subarrays | function to check if array can be split into three equal sum subarrays by removing a pair ; two pointers l and r ; stores prefix sum array ; traverse the array ; two pointer approach ; sum of left subarray ; sum of middle subarray ; sum of right subarray ; print split indices if sum is equal ; move left pointer if lsum < rsum ; move right pointer if rsum > lsum ; move both pointers if lsum = rsum but they are not equal to msum ; if no possible pair exists , print - 1 ; 
def findSplit(arr, N):
    l = 1
    r = N - 2
    sum = [0] * N
    sum[0] = arr[0]
    for i in range(1, N):
        sum[i] = sum[i - 1] + arr[i]
    while (l < r):
        lsum = sum[l - 1]
        msum = sum[r - 1] - sum[l]
        rsum = sum[N - 1] - sum[r]
        if (lsum == msum and msum == rsum):
            print(l, r)
            return
        if (lsum < rsum):
            l += 1
        elif (lsum > rsum):
            r -= 1
        else:
            l += 1
            r -= 1
    print(-1)


if __name__ == "__main__":
    arr = [2, 5, 12, 7, 19, 4, 3]
    N = len(arr)
    findSplit(arr, N)

# Expected output:
2 4
# minimum initial vertices to traverse whole matrix with given conditions | python3 program to find minimum initial vertices to reach whole matrix ; ( n , m ) is current source cell from which we need to do dfs . n and m are total no . of rows and columns . ; marking the vertex as visited ; if below neighbor is valid and has value less than or equal to current cell 's value ; if right neighbor is valid and has value less than or equal to current cell 's value ; if above neighbor is valid and has value less than or equal to current cell 's value ; if left neighbor is valid and has value less than or equal to current cell 's value ; storing the cell value and cell indices in a vector . ; sorting the newly created array according to cell values ; create a visited array for dfs and initialize it as false . ; applying dfs for each vertex with highest value ; if the given vertex is not visited then include it in the set ; 

MAX = 100


def dfs(n, m, visit, adj, N, M):
    visit[n][m] = 1
    if (n + 1 < N and adj[n][m] >= adj[n + 1][m] and not visit[n + 1][m]):
        dfs(n + 1, m, visit, adj, N, M)
    if (m + 1 < M and adj[n][m] >= adj[n][m + 1] and not visit[n][m + 1]):
        dfs(n, m + 1, visit, adj, N, M)
    if (n - 1 >= 0 and adj[n][m] >= adj[n - 1][m] and not visit[n - 1][m]):
        dfs(n - 1, m, visit, adj, N, M)
    if (m - 1 >= 0 and adj[n][m] >= adj[n][m - 1] and not visit[n][m - 1]):
        dfs(n, m - 1, visit, adj, N, M)


def printMinSources(adj, N, M):
    x = []
    for i in range(N):
        for j in range(M):
            x .append([adj[i][j], [i, j]])
    x .sort()
    visit = [[False for i in range(MAX)]for i in range(N)]
    for i in range(len(x) - 1, -1, -1):
        if (not visit[x[i][1][0]][x[i][1][1]]):
            print('{} {}'.format(x[i][1][0], x[i][1][1]))
            dfs(x[i][1][0], x[i][1][1], visit, adj, N, M)


if __name__ == '__main__':
    N = 2
    M = 2
    adj = [[3, 3], [1, 1]]
    printMinSources(adj, N, M)

# Expected output:
0 1