giulio98/xlcost-single-prompt huggingface dataset:
# finding astronauts from different countries | function to perform the dfs traversal to find the count of connected components ; marking vertex visited ; dfs call to neighbour vertices ; if the current node is not visited , then recursively call dfs ; function to find the number of ways to choose two astronauts from the different countries ; stores the adjacency list ; constructing the graph ; stores the visited vertices ; stores the size of every connected components ; dfs call to the graph ; store size of every connected component ; stores the total number of ways to count the pairs ; traverse the array ; print the value of ans ; 

adj = []
visited = []
num = 0


def dfs(v):
    global adj, visited, num
    visited[v] = True
    num += 1
    for i in range(len(adj[v])):
        if (not visited[adj[v][i]]):
            dfs(adj[v][i])


def numberOfPairs(N, arr):
    global adj, visited, num
    adj = []
    for i in range(N):
        adj .append([])
    for i in range(len(arr)):
        adj[arr[i][0]].append(arr[i][1])
        adj[arr[i][1]].append(arr[i][0])
    visited = [False] * (N)
    v = []
    num = 0
    for i in range(N):
        if (not visited[i]):
            dfs(i)
            v .append(num)
            num = 0
    ans = N * int((N - 1) / 2)
    for i in range(len(v)):
        ans -= (v[i] * int((v[i] - 1) / 2))
    ans += 1
    print(ans)


N = 6
arr = [[0, 1], [0, 2], [2, 5]]
numberOfPairs(N, arr)

# Expected output:
9
# count of perfect numbers in given range for q queries | python 3 program for the above approach ; function to check whether a number is perfect number ; stores sum of divisors ; itearate over the range [ 2 , sqrt ( n ) ] ; if sum of divisors is equal to n , then n is a perfect number ; function to find count of perfect numbers in a given range ; stores the count of perfect numbers upto a every number less than max ; iterate over the range [ 1 , max ] ; traverse the array arr [ ] ; print the count of perfect numbers in the range [ arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ] ; 

from math import sqrt
MAX = 100005


def isPerfect(N):
    sum = 1
    for i in range(2, int(sqrt(N)) + 1, 1):
        if (N % i == 0):
            if (i * i != N):
                sum = sum + i + N // i
            else:
                sum = sum + i
    if (sum == N and N != 1):
        return True
    return False


def Query(arr, N):
    prefix = [0 for i in range(MAX + 1)]
    for i in range(2, MAX + 1, 1):
        prefix[i] = prefix[i - 1] + isPerfect(i)
    for i in range(N):
        print(prefix[arr[i][1]] - prefix[arr[i][0] - 1], end=" ")


if __name__ == '__main__':
    arr = [[1, 1000], [1000, 2000], [2000, 3000]]
    N = len(arr)
    Query(arr, N)

# Expected output:
3 0 0
# find any possible two coordinates of rectangle whose two coordinates are given | function to find the remaining two rectangle coordinates ; pairs to store the position of given two coordinates of the rectangle . ; pairs to store the remaining two coordinates of the rectangle . ; traverse through matrix and find pairs p1 and p2 ; first case ; second case ; third case ; print the matrix ; 
def Create_Rectangle(arr, n):
    for i in range(n):
        arr[i] = [i for i in arr[i]]
    p1 = [-1, -1]
    p2 = [-1, -1]
    p3 = []
    p4 = []
    for i in range(n):
        for j in range(n):
            if (arr[i][j] == '1'):
                if (p1[0] == -1):
                    p1 = [i, j]
                else:
                    p2 = [i, j]
    p3 = p1
    p4 = p2
    if (p1[0] == p2[0]):
        p3[0] = (p1[0] + 1) % n
        p4[0] = (p2[0] + 1) % n
    elif (p1[1] == p2[1]):
        p3[1] = (p1[1] + 1) % n
        p4[1] = (p2[1] + 1) % n
    else:
        p3[0], p4[0] = p4[0], p3[0]
    arr[p3[0]][p3[1]] = '1'
    arr[p4[0]][p4[1]] = '1'
    for i in range(n):
        print("".join(arr[i]))


if __name__ == '__main__':
    n = 4
    arr = ["0010", "0000", "1000", "0000"]
    Create_Rectangle(arr, n)

# Expected output:
1010
0000
1010
0000
# sum of all the prime divisors of a number | set 2 | python3 program for the above approach ; function to find sum of prime divisors of the given number n ; add the number 2 if it divides n ; traverse the loop from [ 3 , sqrt ( n ) ] ; if i divides n , add i and divide n ; this condition is to handle the case when n is a prime number greater than 2 ; 

import math


def SumOfPrimeDivisors(n):
    sum = 0
    if n % 2 == 0:
        sum += 2
    while n % 2 == 0:
        n //= 2
    k = int(math .sqrt(n))
    for i in range(3, k + 1, 2):
        if n % i == 0:
            sum += i
        while n % i == 0:
            n //= i
    if n > 2:
        sum += n
    return sum


if __name__ == '__main__':
    n = 10
    print(SumOfPrimeDivisors(n))

# Expected output:
7
# count bases which contains a set bit as the most significant bit in the representation of n | python 3 program for the above approach ; function to count bases having msb of n as a set bit ; store the required count ; iterate over the range [ 2 , n ] ; store the msb of n ; if msb is 1 , then increment the count by 1 ; return the count ; 

import math


def countOfBase(N):
    count = 0
    for i in range(2, N + 1):
        highestPower = int(math .log(N) / math .log(i))
        firstDigit = int(N / int(math .pow(i, highestPower)))
        if (firstDigit == 1):
            count += 1
    return count


N = 6
print(countOfBase(N))

# Expected output:
4
# k | function to find the kth digit from last in an integer n ; if k is less than equal to 0 ; convert integer into string ; if k is greater than length of the temp ; print the k digit from last ; 
def kthDigitFromLast(n, k):
    if (k <= 0):
        print(-1)
        return
    temp = str(n)
    if (k > len(temp)):
        print(-1)
    else:
        print(ord(temp[len(temp) - k]) - ord('0'))


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

# Expected output:
5
# count ways to split array into three non | function to count ways to split array into three subarrays with equal bitwise xor ; stores the xor value of arr [ ] ; update the value of arr_xor ; stores the xor value of prefix and suffix array respectively ; stores the ending points of all the required prefix arrays ; stores the count of suffix arrays whose xor value is equal to the total xor value at each index ; find all prefix arrays with xor value equal to arr_xor ; update pref_xor ; fill the values of suff_inds [ ] ; update suff_xor ; update suff_inds [ i ] ; stores the total number of ways ; count total number of ways ; return the final count ; 
def countWays(arr, N):
    arr_xor = 0
    for i in range(N):
        arr_xor ^= arr[i]
    pref_xor, suff_xor = 0, 0
    pref_ind = []
    suff_inds = [0] * (N + 1)
    for i in range(N):
        pref_xor ^= arr[i]
        if (pref_xor == arr_xor):
            pref_ind .append(i)
    for i in range(N - 1, -1, -1):
        suff_xor ^= arr[i]
        suff_inds[i] += suff_inds[i + 1]
        if (suff_xor == arr_xor):
            suff_inds[i] += 1
    tot_ways = 0
    for idx in pref_ind:
        if (idx < N - 1):
            tot_ways += suff_inds[idx + 2]
    return tot_ways


if __name__ == '__main__':
    arr = [7, 0, 5, 2, 7]
    N = len(arr)
    print(countWays(arr, N))

# Expected output:
2
# count pairs up to n having sum equal to their xor | 2d array for memoization ; recursive function to count pairs ( x , y ) such that x + y = x ^ y ; if the string is traversed completely ; if the current subproblem is already calculated ; if bound = 1 and s [ i ] = = '0' , only ( 0 , 0 ) can be placed ; otherwise ; placing ( 0 , 1 ) and ( 1 , 0 ) are equivalent . hence , multiply by 2. ; place ( 0 , 0 ) at the current position . ; return the answer ; utility function to convert n to its binary representation ; function to count pairs ( x , y ) such that x + y = x ^ y ; convert the number to equivalent binary representation ; print answer returned by recursive function ; 

dp = [[-1 for i in range(2)]for j in range(1000)]


def IsSumEqualsXor(i, n, bound, s):
    if (i == n):
        return 1
    if (dp[i][bound] != -1):
        return dp[i][bound]
    ans = 0
    if (bound and s[i] == '0'):
        ans = IsSumEqualsXor(i + 1, n, 1, s)
    else:
        ans = 2 * IsSumEqualsXor(i + 1, n, bound & (s[i] == '1'), s)
        ans += IsSumEqualsXor(i + 1, n, 0, s)
    dp[i][bound] = ans
    return ans


def convertToBinary(n):
    ans = []
    while (n):
        rem = chr(n % 2 + 48)
        ans .append(rem)
        n //= 2
    ans = ans[::-1]
    return ans


def IsSumEqualsXorUtil(N):
    s = convertToBinary(N)
    print(IsSumEqualsXor(0, len(s), 1, s))


if __name__ == '__main__':
    N = 10
    IsSumEqualsXorUtil(N)

# Expected output:
37
# mean of fourth powers of first n natural numbers | function to find the average of the fourth power of first n natural numbers ; stores the sum of the fourth powers of first n natural numbers ; calculate the sum of fourth power ; return the average ; 
def findAverage(N):
    S = 0
    for i in range(1, N + 1):
        S += i * i * i * i
    return round(S / N, 4)


if __name__ == '__main__':
    N = 3
    print(findAverage(N))

# Expected output:
32.6667
# construct a graph from given degrees of all vertices | a function to print the adjacency matrix . ; n is number of vertices ; for each pair of vertex decrement the degree of both vertex . ; print the result in specified form ; 
def printMat(degseq, n):
    mat = [[0] * n for i in range(n)]
    for i in range(n):
        for j in range(i + 1, n):
            if (degseq[i] > 0 and degseq[j] > 0):
                degseq[i] -= 1
                degseq[j] -= 1
                mat[i][j] = 1
                mat[j][i] = 1
    print(" ", end=" ")
    for i in range(n):
        print(" ", "(", i, ")", end="")
    print()
    print()
    for i in range(n):
        print(" ", "(", i, ")", end="")
        for j in range(n):
            print(" ", mat[i][j], end="")
        print()


if __name__ == '__main__':
    degseq = [2, 2, 1, 1, 1]
    n = len(degseq)
    printMat(degseq, n)

# Expected output:
    ( 0 )  ( 1 )  ( 2 )  ( 3 )  ( 4 )

  ( 0 )  0  1  1  0  0
  ( 1 )  1  0  0  1  0
  ( 2 )  1  0  0  0  0
  ( 3 )  0  1  0  0  0
  ( 4 )  0  0  0  0  0
# decimal equivalent of concatenation of absolute difference of floor and rounded | function to find the decimal equivalent of the new binary array constructed from absolute decimal of floor and the round - off values ; traverse the givenarray from the end ; stores the absolute difference between floor and round - off each array element ; if bit / difference is 1 , then calculate the bit by proper power of 2 and add it to result ; increment the value of power ; print the result ; 
def findDecimal(arr, N):
    power = 0
    result = 0
    for i in range(N - 1, -1, -1):
        bit = abs(int(arr[i]) - round(arr[i]))
        if (bit):
            result += pow(2, power)
        power += 1
    print(result)


arr = [1.2, 2.6, 4.2, 6.9, 3.1, 21.6, 91.2]
N = len(arr)
findDecimal(arr, N)

# Expected output:
42
# calculate money placed in boxes after n days based on 
def totalMoney(N):
    ans = 0
    for i in range(0, N):
        ans += i / 7
        ans += (i % 7 + 1)
    return ans


N = 15
print(totalMoney(N))

# Expected output:
72.0
# sum of absolute differences of indices of occurrences of each array element | set 2 | stores the count of occurrences and previous index of every element ; constructor ; function to calculate the sum of absolute differences of indices of occurrences of array element ; stores the count of elements and their previous indices ; initialize 2 arrays left [ ] and right [ ] of size n ; traverse the given array ; if arr [ i ] is present in the map ; update left [ i ] to 0 and update the value of arr [ i ] in map ; otherwise , get the value from the map and update left [ i ] ; clear the map to calculate right [ ] array ; traverse the array arr [ ] in reverse ; if arr [ i ] is present in themap ; update right [ i ] to 0 and update the value of arr [ i ] in the map ; otherwise get the value from the map and update right [ i ] ; iterate in the range [ 0 , n - 1 ] and print the sum of left [ i ] and right [ i ] as the result ; 

class pair:
    def __init__(self, count, prevIndex):
        self .count = count
        self .prevIndex = prevIndex


def findSum(arr, n):
    map = {}
    left = [0 for i in range(n)]
    right = [0 for i in range(n)]
    for i in range(n):
        if (arr[i]not in map):
            left[i] = 0
            map[arr[i]] = pair(1, i)
        else:
            tmp = map[arr[i]]
            left[i] = (tmp .count) * (i - tmp .prevIndex) + \
                left[tmp .prevIndex]
            map[arr[i]] = pair(tmp .count + 1, i)
    map .clear()
    for i in range(n - 1, -1, -1):
        if (arr[i]not in map):
            right[i] = 0
            map[arr[i]] = pair(1, i)
        else:
            tmp = map[arr[i]]
            right[i] = (tmp .count) * (abs(i - tmp .prevIndex)) + \
                right[tmp .prevIndex]
            map[arr[i]] = pair(tmp .count + 1, i)
    for i in range(n):
        print(left[i] + right[i], end=" ")


arr = [1, 3, 1, 1, 2]
N = len(arr)
findSum(arr, N)

# Expected output:
5 0 3 4 0
# convert a number to another by dividing by its factor or removing first occurrence of a digit from an array | python3 program for the above approach ; function to check if a digit x is present in the number n or not ; convert n to string ; traverse the num ; return first occurrence of the digit x ; function to remove the character at a given index from the number ; convert n to string ; store the resultant string ; traverse the num ; if the number becomes empty after deletion , then return - 1 ; return the number ; function to check if a can be reduced to b by performing the operations any number of times ; create a queue ; push a into the queue ; hashmap to check if the element is present in the queue or not ; set a as visited ; iterate while the queue is not empty ; store the front value of the queue and pop it from it ; if top is equal to b , then return true ; traverse the array , d [ ] ; divide top by d [ i ] if it is possible and push the result in q ; if d [ i ] is present at the top ; remove the first occurrence of d [ i ] from the top and store the new number ; push newelement into the queue q ; return false if a can not be reduced to b ; 

from collections import deque


def isPresent(n, x):
    num = str(n)
    for i in range(len(num)):
        if ((ord(num[i]) - ord('0')) == x):
            return i
    return -1


def removeDigit(n, index):
    num = str(n)
    ans = ""
    for i in range(len(num)):
        if (i != index):
            ans += num[i]
    if (ans == "" or (len(ans) == 1 and ans[0] == '0')):
        return -1
    x = int(ans)
    return x


def reduceNtoX(a, b, d, n):
    q = deque()
    q .append(a)
    visited = {}
    visited[a] = True
    while (len(q) > 0):
        top = q .popleft()
        if (top < 0):
            continue
        if (top == b):
            return True
        for i in range(n):
            if (d[i] != 0 and top % d[i] == 0 and (top // d[i]not in visited)):
                q .append(top // d[i])
                visited[top // d[i]] = True
            index = isPresent(top, d[i])
            if (index != -1):
                newElement = removeDigit(top, index)
                if (newElement != -1 and (newElement not in visited)):
                    q .append(newElement)
                    visited[newElement] = True
    return False


if __name__ == '__main__':
    A, B = 5643, 81
    D = [3, 8, 1]
    N = len(D)
    if (reduceNtoX(A, B, D, N)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# prime triplets consisting of values up to n having difference between two elements equal to the third | python3 program for the above approach ; stores 1 and 0 at indices which are prime and non - prime respectively ; function to find all prime numbers from the range [ 0 , n ] ; iterate over the range [ 2 , sqrt ( n ) ] ; if p is a prime ; update all tultiples of p as false ; function to find all prime triplets satisfying the given conditions ; generate all primes up to n ;  ; iterate over the range [ 3 , n ] ; check for the condition ; store the triplets ; print all the stored triplets ; 

from math import sqrt
prime = [True for i in range(100000)]


def SieveOfEratosthenes(n):
    for p in range(2, int(sqrt(n)) + 1, 1):
        if (prime[p]):
            for i in range(p * p, n + 1, p):
                prime[i] = False


def findTriplets(N):
    SieveOfEratosthenes(N)
    V = []
    for i in range(3, N + 1, 1):
        if (2 + i <= N and prime[i] and prime[2 + i]):
            V .append([2, i, i + 2])
    for i in range(len(V)):
        print((V[i][0], V[i][1], V[i][2]))


if __name__ == '__main__':
    N = 8
    findTriplets(N)

# Expected output:
(2, 3, 5)
(2, 5, 7)
# smallest number which is not coprime with any element of an array | python 3 program for the above approach ; function check if a number is prime or not ; corner cases ; check if n is divisible by 2 or 3 ; check for every 6 th number . the above checking allows to skip middle 5 numbers ; function to store primes in an array ; function to find the smallest number which is not coprime with any element of the array arr [ ] ; store the prime numbers ; function call to fill the prime numbers ; stores the answer ; generate all non - empty subsets of the primes [ ] array ; stores product of the primes ; checks if temp is coprime with the array or not ; check if the product temp is not coprime with the whole array ; if the product is not co - prime with the array ; print the answer ; 

from math import sqrt, gcd
import sys
MAX = 50


def isPrime(n):
    if (n <= 1):
        return False
    if (n <= 3):
        return True
    if (n % 2 == 0 or n % 3 == 0):
        return False
    for i in range(5, int(sqrt(n)) + 1, 6):
        if (n % i == 0 or n % (i + 2) == 0):
            return False
    return True


def findPrime(primes):
    global MAX
    for i in range(2, MAX + 1, 1):
        if (isPrime(i)):
            primes .append(i)


def findMinimumNumber(arr, N):
    primes = []
    findPrime(primes)
    ans = sys .maxsize
    n = len(primes)
    for i in range(1, (1 << n), 1):
        temp = 1
        for j in range(n):
            if (i & (1 << j)):
                temp *= primes[j]
        check = True
        for k in range(N):
            if (gcd(temp, arr[k]) == 1):
                check = False
                break
        if (check):
            ans = min(ans, temp)
    print(ans)


if __name__ == '__main__':
    arr = [3, 4, 6, 7, 8, 9, 10]
    N = len(arr)
    findMinimumNumber(arr, N)

# Expected output:
42
# count numbers from a given range that can be expressed as sum of digits raised to the power of count of digits | python 3 program for the above approach ; function to check if a number n can be expressed as sum of its digits raised to the power of the count of digits ; stores the number of digits ; stores the resultant number ; return true if both the numbers are same ; function to precompute and store for all numbers whether they can be expressed ; mark all the index which are plus perfect number ; if true , then update the value at this index ; compute prefix sum of the array ; function to count array elements that can be expressed as the sum of digits raised to the power of count of digits ; precompute the results ; traverse the queries ; print the resultant count ; 

R = 100005
arr = [0 for i in range(R)]


def canExpress(N):
    temp = N
    n = 0
    while (N != 0):
        N //= 10
        n += 1
    N = temp
    sum = 0
    while (N != 0):
        sum += pow(N % 10, n)
        N //= 10
    return (sum == temp)


def precompute():
    for i in range(1, R, 1):
        if (canExpress(i)):
            arr[i] = 1
    for i in range(1, R, 1):
        arr[i] += arr[i - 1]


def countNumbers(queries, N):
    precompute()
    for i in range(N):
        L1 = queries[i][0]
        R1 = queries[i][1]
        print((arr[R1] - arr[L1 - 1]), end=" ")


if __name__ == '__main__':
    queries = [[1, 400], [1, 9]]
    N = len(queries)
    countNumbers(queries, N)

# Expected output:
12 9
# queries to calculate sum of the path from root to a given node in 
def sumOfNodeInAPath(node_value):
    sum_of_node = 0
    while (node_value):
        sum_of_node += node_value
        node_value //= 2
    print(sum_of_node, end=" ")


def findSum(Q):
    for i in range(len(Q)):
        node_value = Q[i]
        sumOfNodeInAPath(node_value)
        print(end="")


arr = [1, 5, 20, 100]
findSum(arr)

# Expected output:
1 8 38 197
# minimum removals required to make frequency of all remaining array elements equal | python 3 program for the above approach ; function to count the minimum removals required to make frequency of all array elements equal ; stores frequency of all array elements ; traverse the array ; stores all the frequencies ; traverse the map ; sort the frequencies ; count of frequencies ; stores the final count ; traverse the vector ; count the number of removals for each frequency and update the minimum removals required ; print the final count ; 

from collections import defaultdict


def minDeletions(arr, N):
    freq = defaultdict(int)
    for i in range(N):
        freq[arr[i]] += 1
    v = []
    for z in freq .keys():
        v .append(freq[z])
    v .sort()
    size = len(v)
    ans = N - (v[0] * size)
    for i in range(1, len(v)):
        if (v[i] != v[i - 1]):
            safe = v[i] * (size - i)
            ans = min(ans, N - safe)
    print(ans)


if __name__ == "__main__":
    arr = [2, 4, 3, 2, 5, 3]
    N = len(arr)
    minDeletions(arr, N)

# Expected output:
2
# number of sink nodes in a graph | return the number of sink nodes . ; array for marking the non - sink node . ; marking the non - sink node . ; counting the sink nodes . ; 
def countSink(n, m, edgeFrom, edgeTo):
    mark = [0] * (n + 1)
    for i in range(m):
        mark[edgeFrom[i]] = 1
    count = 0
    for i in range(1, n + 1):
        if (not mark[i]):
            count += 1
    return count


if __name__ == '__main__':
    n = 4
    m = 2
    edgeFrom = [2, 4]
    edgeTo = [3, 3]
    print(countSink(n, m, edgeFrom, edgeTo))

# Expected output:
2
# largest subset of graph vertices with edges of 2 or more colors | number of vertices ; function to calculate max subset size ; set for number of vertices ; loop for deletion of vertex from set ; if subset has only 1 vertex return 0 ; for each vertex iterate and keep removing a vertix while we find a vertex with all edges of same color . ; note down different color values for each vertex ; if only one color is found erase that vertex ( bad vertex ) ; if no vertex was removed in the above loop . ; 

N = 6


def subsetGraph(C):
    global N
    vertices = set()
    for i in range(N):
        vertices .add(i)
    while (len(vertices) != 0):
        if (len(vertices) == 1):
            return 1
        someone_removed = False
        for x in vertices:
            values = set()
            for y in vertices:
                if (y != x):
                    values .add(C[x][y])
            if (len(values) == 1):
                vertices .remove(x)
                someone_removed = True
                break
        if (not someone_removed):
            break
    return len(vertices)


C = [[0, 9, 2, 4, 7, 8], [9, 0, 9, 9, 7, 9], [2, 9, 0, 3, 7, 6],
     [4, 9, 3, 0, 7, 1], [7, 7, 7, 7, 0, 7], [8, 9, 6, 1, 7, 0]]
print(subsetGraph(C))

# Expected output:
4