giulio98/xlcost-single-prompt huggingface dataset:
# sum of bitwise or of each array element of an array with all elements of another array | function to compute sum of bitwise or of each element in arr1 [ ] with all elements of the array arr2 [ ] ; declaring an array of size 32 to store the count of each bit ; traverse the array arr1 [ ] ; current bit position ; while num exceeds 0 ; checks if i - th bit is set or not ; increment the count at bit_position by one ; increment bit_position ; right shift the num by one ; traverse in the arr2 [ ] ; store the ith bit value ; total required sum ; traverse in the range [ 0 , 31 ] ; check if current bit is set ; increment the bitwise sum by n * ( 2 ^ i ) ; right shift num by one ; left shift valee_at_that_bit by one ; print the sum obtained for ith number in arr1 [ ] ; given arr1 [ ] ; 
def Bitwise_OR_sum_i(arr1, arr2, M, N):
    frequency = [0] * 32
    for i in range(N):
        bit_position = 0
        num = arr1[i]
        while (num):
            if (num & 1 != 0):
                frequency[bit_position] += 1
            bit_position += 1
            num >>= 1
    for i in range(M):
        num = arr2[i]
        value_at_that_bit = 1
        bitwise_OR_sum = 0
        for bit_position in range(32):
            if (num & 1 != 0):
                bitwise_OR_sum += N * value_at_that_bit
            else:
                bitwise_OR_sum += (frequency[bit_position] * value_at_that_bit)
            num >>= 1
            value_at_that_bit <<= 1
        print(bitwise_OR_sum, end=" ")
    return


arr1 = [1, 2, 3]
arr2 = [1, 2, 3]
N = len(arr1)
M = len(arr2)
Bitwise_OR_sum_i(arr1, arr2, M, N)

# Expected output:
7 8 9
# count pairs from given array with bitwise or equal to k | function that counts the pairs from the array whose bitwise or is k ; stores the required count of pairs ; generate all possible pairs ; perform or operation ; if bitwise or is equal to k , increment count ; print the total count ; 
def countPairs(arr, k, size):
    count = 0
    for i in range(size - 1):
        for j in range(i + 1, size):
            x = arr[i] | arr[j]
            if (x == k):
                count += 1
    print(count)


arr = [2, 38, 44, 29, 62]
K = 46
N = len(arr)
countPairs(arr, K, N)

# Expected output:
2
# count nodes having bitwise xor of all edges in their path from the root equal to k | initialize the adjacency list to represent the tree ; marks visited / unvisited vertices ; stores the required count of nodes ; dfs to visit each vertex ; mark the current node as visited ; update the counter xor is k ; visit adjacent nodes ; calculate bitwise xor of edges in the path ; recursive call to dfs function ; function to construct the tree and prrequired count of nodes ; add edges ; print answer ; 

adj = [[]for i in range(100005)]
visited = [0] * 100005
ans = 0


def dfs(node, xorr, k):
    global ans
    visited[node] = 1
    if (node != 1 and xorr == k):
        ans += 1
    for x in adj[node]:
        if (not visited[x[0]]):
            xorr1 = xorr ^ x[1]
            dfs(x[0], xorr1, k)


def countNodes(N, K, R, edges):
    for i in range(N - 1):
        u = edges[i][0]
        v = edges[i][1]
        w = edges[i][2]
        adj[u].append([v, w])
        adj[v].append([u, w])
    dfs(R, 0, K)
    print(ans)


if __name__ == '__main__':
    K = 0
    R = 1
    edges = [[1, 2, 3], [1, 3, 1], [2, 4, 3], [2, 5, 4], [3, 6, 1], [3, 7, 2]]
    N = len(edges)
    countNodes(N, K, R, edges)

# Expected output:
2
# bitwise operations on subarrays of size k | function to find the minimum xor of the subarray of size k ; k must be smaller than or equal to n ; initialize the beginning index of result ; compute xor sum of first subarray of size k ; initialize minimum xor sum as current xor ; traverse from ( k + 1 ) ' th ▁ ▁ element ▁ to ▁ n ' th element ; xor with current item and first item of previous subarray ; update result if needed ; print the minimum xor ; 
def findMinXORSubarray(arr, n, k):
    if (n < k):
        return
    res_index = 0
    curr_xor = 0
    for i in range(k):
        curr_xor ^= arr[i]
    min_xor = curr_xor
    for i in range(k, n):
        curr_xor ^= (arr[i] ^ arr[i - k])
        if (curr_xor < min_xor):
            min_xor = curr_xor
            res_index = (i - k + 1)
    print(min_xor)


if __name__ == '__main__':
    arr = [3, 7, 90, 20, 10, 50, 40]
    k = 3
    n = len(arr)
    findMinXORSubarray(arr, n, k)

# Expected output:
16
# maximum number of consecutive 1 s after flipping all 0 s in a k length subarray | function to find the maximum number of consecutive 1 's after flipping all zero in a k length subarray ; initialize variable ; iterate unil n - k + 1 as we have to go till i + k ; iterate in the array in left direction till you get 1 else break ; iterate in the array in right direction till you get 1 else break ; compute the maximum length ; return the length ; 
def findmax(arr, n, k):
    trav, i = 0, 0
    c = 0
    maximum = 0
    while i < n - k + 1:
        trav = i - 1
        c = 0
        while trav >= 0 and arr[trav] == 1:
            trav -= 1
            c += 1
        trav = i + k
        while (trav < n and arr[trav] == 1):
            trav += 1
            c += 1
        c += k
        if (c > maximum):
            maximum = c
        i += 1
    return maximum


if __name__ == '__main__':
    k = 3
    arr = [0, 0, 1, 1, 0, 0, 0, 0]
    n = len(arr)
    ans = findmax(arr, n, k)
    print(ans)

# Expected output:
5
# count of elements which cannot form any pair whose sum is power of 2 | python3 program to count of array elements which do not form a pair with sum equal to a power of 2 with any other array element ; function to calculate and return the count of elements ; stores the frequencies of every array element ; stores the count of removals ; for every element , check if it can form a sum equal to any power of 2 with any other element ; store pow ( 2 , j ) - a [ i ] ; check if s is present in the array ; if frequency of s exceeds 1 ; if s has frequency 1 but is different from a [ i ] ; pair possible ; if no pair possible for the current element ; return the answer ; 

from collections import defaultdict


def powerOfTwo(a, n):
    mp = defaultdict(int)
    for i in range(n):
        mp[a[i]] += 1
    count = 0
    for i in range(n):
        f = False
        for j in range(31):
            s = (1 << j) - a[i]
            if (s in mp and (mp[s] > 1 or mp[s] == 1 and s != a[i])):
                f = True
        if (f == False):
            count += 1
    return count


if __name__ == "__main__":
    a = [6, 2, 11]
    n = len(a)
    print(powerOfTwo(a, n))

# Expected output:
1
# construct the array using given bitwise and , or and xor | python3 program for the above approach ; function to find the array ; loop through all bits in number ; if bit is set in and then set it in every element of the array ; if bit is not set in and ; but set in b ( or ) ; set bit position in first element ; if bit is not set in c then set it in second element to keep xor as zero for bit position ; calculate and , or and xor of array ; check if values are equal or not ; if not , then array is not possible ; 

import sys


def findArray(n, a, b, c):
    arr = [0] * (n + 1)
    for bit in range(30, -1, -1):
        set = a & (1 << bit)
        if (set):
            for i in range(n):
                arr[i] |= set
        else:
            if (b & (1 << bit)):
                arr[0] |= (1 << bit)
                if (not (c & (1 << bit))):
                    arr[1] |= (1 << bit)
    aa = sys .maxsize
    bb = 0
    cc = 0
    for i in range(n):
        aa &= arr[i]
        bb |= arr[i]
        cc ^= arr[i]
    if (a == aa and b == bb and c == cc):
        for i in range(n):
            print(arr[i], end=" ")
    else:
        print("-1")


if __name__ == "__main__":
    n = 3
    a = 4
    b = 6
    c = 6
    findArray(n, a, b, c)

# Expected output:
6 4 4
# minimum xor of or and and of any pair in the array | function to find the minimum value of xor of and and or of any pair in the given array ; sort the array ; traverse the array arr [ ] ; compare and find the minimum xor value of an array . ; return the final answer ; 
def maxAndXor(arr, n):
    ans = float('inf')
    arr .sort()
    for i in range(n - 1):
        ans = min(ans, arr[i] ^ arr[i + 1])
    return ans


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

# Expected output:
1
# count of subarrays of size k with elements having even frequencies | function to return count of required subarrays ; if k is odd ; not possible to have any such subarrays ; stores the starting index of every subarrays ; stores the count of required subarrays ; stores xor of the current subarray . ; xor of first subarray of size k ; if all elements appear even number of times , increase the count of such subarrays ; remove the starting element from the current subarray ; traverse the array for the remaining subarrays ; update xor by adding the last element of the current subarray ; increment i ; if currxor becomes 0 , then increment count ; update currxor by removing the starting element of the current subarray ; return count ; 
def countSubarray(arr, K, N):
    if (K % 2 != 0):
        return 0
    if (N < K):
        return 0
    start = 0
    i = 0
    count = 0
    currXor = arr[i]
    i += 1
    while (i < K):
        currXor ^= arr[i]
        i += 1
    if (currXor == 0):
        count += 1
    currXor ^= arr[start]
    start += 1
    while (i < N):
        currXor ^= arr[i]
        i += 1
        if (currXor == 0):
            count += 1
        currXor ^= arr[start]
        start += 1
    return count


if __name__ == '__main__':
    arr = [2, 4, 4, 2, 2, 4]
    K = 4
    N = len(arr)
    print(countSubarray(arr, K, N))

# Expected output:
3
# count of even and odd set bit array elements after xor with k for q queries | python3 program to count number of even and odd set bits elements after xor with a given element ; store the count of set bits ; brian kernighan 's algorithm ; function to solve q queries ; store set bits in x ; count set bits of x ; 

even = 0
odd = 0


def keep_count(arr, N):
    global even
    global odd
    for i in range(N):
        count = 0
        while (arr[i] != 0):
            arr[i] = (arr[i] - 1) & arr[i]
            count += 1
        if (count % 2 == 0):
            even += 1
        else:
            odd += 1
    return


def solveQueries(arr, n, q, m):
    global even
    global odd
    keep_count(arr, n)
    for i in range(m):
        X = q[i]
        count = 0
        while (X != 0):
            X = (X - 1) & X
            count += 1
        if (count % 2 == 0):
            print(even, odd)
        else:
            print(odd, even)


if __name__ == '__main__':
    arr = [2, 7, 4, 5, 3]
    n = len(arr)
    q = [3, 4, 12, 6]
    m = len(q)
    solveQueries(arr, n, q, m)

# Expected output:
2 3
3 2
2 3
2 3
# largest number in the array having frequency same as value | function to find the largest number whose frequency is equal to itself . ; find the maximum element in the array ; 
def findLargestNumber(arr):
    k = max(arr)
    m = [0] * (k + 1)
    for n in arr:
        m[n] += 1
    for n in range(len(arr) - 1, 0, -1):
        if (n == m[n]):
            return n
    return -1


if __name__ == '__main__':
    arr = [3, 2, 5, 2, 4, 5]
    print(findLargestNumber(arr))

# Expected output:
2
# largest number in the array having frequency same as value | function to find the largest number whose frequency is equal to itself . ; adding 65536 to keep the count of the current number ; right shifting by 16 bits to find the count of the number i ; 
def findLargestNumber(arr, n):
    for i in range(n):
        arr[i] &= 0xFFFF
        if (arr[i] <= n):
            arr[i] += 0x10000
    for i in range(n - 1, 0, -1):
        if ((arr[i] >> 16) == i):
            return i + 1
    return -1


if __name__ == '__main__':
    arr = [3, 2, 5, 5, 2, 4, 5]
    n = len(arr)
    print(findLargestNumber(arr, n))

# Expected output:
2
# convert numbers into binary representation and add them without carry | function returns sum of both the binary number without carry ; xor of n and m ; 
def NoCarrySum(N, M):
    return N ^ M


N = 37
M = 12
print(NoCarrySum(N, M))

# Expected output:
41
# check if all the set bits of the binary representation of n are at least k places away | python3 program to check if all the set bits of the binary representation of n are at least k places away . ; initialize check and count with 0 ; the i - th bit is a set bit ; this is the first set bit so , start calculating all the distances between consecutive bits from here ; if count is less than k return false ; adding the count as the number of zeroes increase between set bits ; 
def CheckBits(N, K):
    check = 0
    count = 0
    for i in range(31, -1, -1):
        if ((1 << i) & N):
            if (check == 0):
                check = 1
            else:
                if (count < K):
                    return False
            count = 0
        else:
            count += 1
    return True


if __name__ == "__main__":
    N = 5
    K = 1
    if (CheckBits(N, K)):
        print("YES")
    else:
        print("NO")

# Expected output:
YES
# minimize bits to be flipped in x and y such that their bitwise or is equal to z | this function returns minimum number of bits to be flipped in x and y to make x | y = z ; if current bit in z is set and is also set in either of x or y or both ; if current bit in z is set and is unset in both x and y ; set that bit in either x or y ; if current bit in z is unset and is set in both x and y ; unset the bit in both x and y ; if current bit in z is unset and is set in either x or y ; unset that set bit ; 
def minimumFlips(X, Y, Z):
    res = 0
    while (X > 0 or Y > 0 or Z > 0):
        if (((X & 1) or (Y & 1)) and (Z & 1)):
            X = X >> 1
            Y = Y >> 1
            Z = Z >> 1
            continue
        elif (not (X & 1) and not (Y & 1) and (Z & 1)):
            res += 1
        elif ((X & 1) or (Y & 1) == 1):
            if ((X & 1) and (Y & 1) and not (Z & 1)):
                res += 2
            elif (((X & 1) or (Y & 1)) and not (Z & 1)):
                res += 1
        X = X >> 1
        Y = Y >> 1
        Z = Z >> 1
    return res


if __name__ == "__main__":
    X = 5
    Y = 8
    Z = 6
    print(minimumFlips(X, Y, Z))

# Expected output:
3
# count subsequences with same values of bitwise and , or and xor | ''function for finding count of possible subsequence ; '' creating a map to count the frequency of each element ; store frequency of each element ; iterate through the map ; add all possible combination for key equal zero ; add all ( odd number of elements ) possible combination for key other than zero ; 
def countSubseq(arr, n):
    count = 0
    mp = {}
    for x in arr:
        if x in mp .keys():
            mp[x] += 1
        else:
            mp[x] = 1
    for i in mp .keys():
        if (i == 0):
            count += pow(2, mp[i]) - 1
        else:
            count += pow(2, mp[i] - 1)
    return count


arr = [2, 2, 2, 5, 6]
n = len(arr)
print(countSubseq(arr, n))

# Expected output:
6
# choose an integer k such that maximum of the xor values of k with all array elements is minimized | function to calculate minimum possible value of the maximum xor in an array ; base case ; divide elements into two sections ; traverse all elements of current section and divide in two groups ; check if one of the sections is empty ; explore both the possibilities using recursion ; function to calculate minimum xor value ; start recursion from the most significant pos position ; 
def calculate(section, pos):
    if (pos < 0):
        return 0
    on_section = []
    off_section = []
    for el in section:
        if (((el >> pos) & 1) == 0):
            off_section .append(el)
        else:
            on_section .append(el)
    if (len(off_section) == 0):
        return calculate(on_section, pos - 1)
    if (len(on_section) == 0):
        return calculate(off_section, pos - 1)
    return min(calculate(off_section, pos - 1),
               calculate(on_section, pos - 1)) + (1 << pos)


def minXorValue(a, n):
    section = []
    for i in range(n):
        section .append(a[i])
    return calculate(section, 30)


if __name__ == "__main__":
    N = 4
    A = [3, 2, 5, 6]
    print(minXorValue(A, N))

# Expected output:
5
# program to find the nth natural number with exactly two bits set | function to find the nth number with exactly two bits set ; keep incrementing until we reach the partition of ' n ' stored in bit_l ; set the rightmost bit based on bit_r ; 
def findNthNum(N):
    bit_L = 1
    last_num = 0
    while (bit_L * (bit_L + 1) / 2 < N):
        last_num = last_num + bit_L
        bit_L += 1
    bit_R = N - last_num - 1
    print((1 << bit_L) + (1 << bit_R))


if __name__ == '__main__':
    N = 13
    findNthNum(N)

# Expected output:
36
# xor of all prime numbers in an array at positions divisible by k | python3 program to find xor of all prime numbers in an array at positions divisible by k ; 0 and 1 are not prime numbers ; if prime [ p ] is not changed , then it is a prime ; update all multiples of p ; function to find the required xor ; to store xor of the primes ; traverse the array ; if the number is a prime ; if index is divisible by k ; print the xor ; 

MAX = 1000005


def SieveOfEratosthenes(prime):
    prime[1] = False
    prime[0] = False
    for p in range(2, int(MAX ** (1 / 2))):
        if (prime[p]):
            for i in range(p * 2, MAX, p):
                prime[i] = False


def prime_xor(arr, n, k):
    prime = [True] * MAX
    SieveOfEratosthenes(prime)
    ans = 0
    for i in range(n):
        if (prime[arr[i]]):
            if ((i + 1) % k == 0):
                ans ^= arr[i]
    print(ans)


if __name__ == "__main__":
    arr = [2, 3, 5, 7, 11, 8]
    n = len(arr)
    K = 2
    prime_xor(arr, n, K)

# Expected output:
4
# find xor of all elements in an array | function to find the xor of all elements in the array ; resultant variable ; iterating through every element in the array ; find xor with the result ; return the xor ; 
def xorOfArray(arr, n):
    xor_arr = 0
    for i in range(n):
        xor_arr = xor_arr ^ arr[i]
    return xor_arr


if __name__ == '__main__':
    arr = [3, 9, 12, 13, 15]
    n = len(arr)
    print(xorOfArray(arr, n))

# Expected output:
4
# count of even set bits between xor of two arrays | function that count the xor of b with all the element in a having even set bit ; count the set bits in a [ i ] ; check for even or odd ; to store the count of element for b such that xor with all the element in a having even set bit ; count set bit for b [ i ] ; check for even or odd ; 
def countEvenBit(A, B, n, m):
    i, j, cntOdd = 0, 0, 0
    cntEven = 0
    for i in range(n):
        x = bin(A[i])[2:].count('1')
        if (x & 1):
            cntEven += 1
        else:
            cntOdd += 1
    CountB = [0] * m
    for i in range(m):
        x = bin(B[i])[2:].count('1')
        if (x & 1):
            CountB[i] = cntEven
        else:
            CountB[i] = cntOdd
    for i in range(m):
        print(CountB[i], end=" ")


if __name__ == '__main__':
    A = [4, 2, 15, 9, 8, 8]
    B = [3, 4, 22]
    countEvenBit(A, B, 6, 3)

# Expected output:
2 4 4
# check if a number is odd or even using bitwise operators | returns true if n is even , else odd ; n ^ 1 is n + 1 , then even , else odd ; 
def isEven(n):
    if (n ^ 1 == n + 1):
        return True
    else:
        return False


if __name__ == "__main__":
    n = 100
    print("Even")if isEven(n)else print("Odd")

# Expected output:
Even
# bitwise or ( | ) of all even number from 1 to n | function to return the bitwise or of all the even numbers upto n ; initialize result as 2 ; 
def bitwiseOrTillN(n):
    result = 2
    for i in range(4, n + 1, 2):
        result = result | i
    return result


n = 10
print(bitwiseOrTillN(n))

# Expected output:
14
# bitwise or ( | ) of all even number from 1 to n | python3 implementation of the above approach ; function to return the bitwise or of all even numbers upto n ; for value less than 2 ; count total number of bits in bitwise or all bits will be set except last bit ; compute 2 to the power bitcount and subtract 2 ; 

from math import log2


def bitwiseOrTillN(n):
    if (n < 2):
        return 0
    bitCount = int(log2(n)) + 1
    return pow(2, bitCount) - 2


if __name__ == "__main__":
    n = 10
    print(bitwiseOrTillN(n))

# Expected output:
14
# generating n | function to generating n - bit gray code starting from k ; generate gray code of corresponding binary number of integer i . ; 
def genSequence(n, val):
    for i in range(1 << n):
        x = i ^ (i >> 1) ^ val
        print(x, end=" ")


if __name__ == "__main__":
    n = 3
    k = 2
    genSequence(n, k)

# Expected output:
2 3 1 0 4 5 7 6
# winner in the rock | function to return the winner of the game ; both the players chose to play the same move ; player a wins the game ; function to perform the queries ; 
def winner(moves):
    data = dict()
    data['R'] = 0
    data['P'] = 1
    data['S'] = 2
    if (moves[0] == moves[1]):
        return "Draw"
    if (((data[moves[0]] | 1 << (2)) - (data[moves[1]] | 0 << (2))) % 3):
        return "A"
    return "B"


def performQueries(arr, n):
    for i in range(n):
        print(winner(arr[i]))


arr = ["RS", "SR", "SP", "PP"]
n = len(arr)
performQueries(arr, n)

# Expected output:
A
B
A
Draw
# maximum number of consecutive 1 's in binary representation of all the array elements | function to return the count of maximum consecutive 1 s in the binary representation of x ; initialize result ; count the number of iterations to reach x = 0. ; this operation reduces length of every sequence of 1 s by one ; function to return the count of maximum consecutive 1 s in the binary representation among all the elements of arr [ ] ; to store the answer ; for every element of the array ; count of maximum consecutive 1 s in the binary representation of the current element ; update the maximum count so far ; 
def maxConsecutiveOnes(x):
    count = 0
    while (x != 0):
        x = (x & (x << 1))
        count += 1
    return count


def maxOnes(arr, n):
    ans = 0
    for i in range(n):
        currMax = maxConsecutiveOnes(arr[i])
        ans = max(ans, currMax)
    return ans


if __name__ == "__main__":
    arr = [1, 2, 3, 4]
    n = len(arr)
    print(maxOnes(arr, n))

# Expected output:
2
# maximum bitwise or pair from a range | function to return the maximum bitwise or possible among all the possible pairs ; check for every possible pair ; maximum among all ( i , j ) pairs ; 
def maxOR(L, R):
    maximum = -10 ** 9
    for i in range(L, R):
        for j in range(i + 1, R + 1):
            maximum = max(maximum, (i & j))
    return maximum


L = 4
R = 5
print(maxOR(L, R))

# Expected output:
4
# maximum bitwise or pair from a range | python3 implementation of the approach ; function to return the maximum bitwise or possible among all the possible pairs ; if there is only a single value in the range [ l , r ] ; loop through each bit from msb to lsb ; msbs where the bits differ , all bits from that bit are set ; if msbs are same , then ans bit is same as that of bit of right or left limit ; 

MAX = 64


def maxOR(L, R):
    if (L == R):
        return L
    ans = 0
    for i in range(MAX - 1, -1, -1):
        p = 1 << i
        lbit = (L >> i) & 1
        rbit = (R >> i) & 1
        if ((rbit == 1) and (lbit == 0)):
            ans += (p << 1) - 1
            break
        if (rbit == 1):
            ans += p
    return ans


if __name__ == "__main__":
    L = 4
    R = 5
    print(maxOR(L, R))

# Expected output:
5