giulio98/xlcost-single-prompt huggingface dataset:
# longest subsequence with a given and value | o ( n ) | function to return the required length ; to store the filtered numbers ; filtering the numbers ; if there are no elements to check ; find the or of all the filtered elements ; check if the or is equal to m ; 
def findLen(arr, n, m):
    filter = []
    for i in range(n):
        if ((arr[i] & m) == m):
            filter .append(arr[i])
    if (len(filter) == 0):
        return 0
    c_and = filter[0]
    for i in range(1, len(filter)):
        c_and &= filter[i]
    if (c_and == m):
        return len(filter)


if __name__ == "__main__":
    arr = [7, 3, 3, 1, 3]
    n = len(arr)
    m = 3
    print(findLen(arr, n, m))

# Expected output:
4
# longest sub | function to return the required length ; to store the filtered numbers ; filtering the numbers ; if there are no elements to check ; find the or of all the filtered elements ; check if the or is equal to m ; 
def findLen(arr, n, m):
    filter = []
    for i in range(n):
        if ((arr[i] | m) == m):
            filter .append(arr[i])
    if (len(filter) == 0):
        return 0
    c_or = filter[0]
    for i in range(1, len(filter)):
        c_or |= filter[i]
    if (c_or == m):
        return len(filter)


if __name__ == "__main__":
    arr = [7, 3, 3, 1, 3]
    n = len(arr)
    m = 3
    print(findLen(arr, n, m))

# Expected output:
4
# program to toggle k | function to toggle the kth bit of n ; 
def toggleBit(n, k):
    return (n ^ (1 << (k - 1)))


if __name__ == "__main__":
    n = 5
    k = 2
    print(toggleBit(n, k))

# Expected output:
7
# program to clear k | function to clear the kth bit of n ; 
def clearBit(n, k):
    return (n & (~(1 << (k - 1))))


n = 5
k = 1
print(clearBit(n, k))

# Expected output:
4
# maximize the expression | bit manipulation | python3 implementation of the approach ; function to return the value of the maximized expression ; int can have 32 bits ; consider the ith bit of d to be 1 ; calculate the value of ( b and bitofd ) ; check if bitofd satisfies ( b and d = d ) ; check if bitofd can maximize ( a xor d ) ; note that we do not need to consider ith bit of d to be 0 because if above condition are not satisfied then value of result will not change which is similar to considering bitofd = 0 as result xor 0 = result ; 

MAX = 32


def maximizeExpression(a, b):
    result = a
    for bit in range(MAX - 1, -1, -1):
        bitOfD = 1 << bit
        x = b & bitOfD
        if (x == bitOfD):
            y = result & bitOfD
            if (y == 0):
                result = result ^ bitOfD
    return result


a = 11
b = 14
print(maximizeExpression(a, b))

# Expected output:
15
# find number of subarrays with xor value a power of 2 | python3 program to count number of subarrays with bitwise - xor as power of 2 ; function to find number of subarrays ; hash map to store prefix xor values ; when no element is selected ; check for all the powers of 2 , till a max value ; insert current prefixxor in hash map ; 

MAX = 10


def findSubarray(array, n):
    mp = dict()
    mp[0] = 1
    answer = 0
    preXor = 0
    for i in range(n):
        value = 1
        preXor ^= array[i]
        for j in range(1, MAX + 1):
            Y = value ^ preXor
            if (Y in mp .keys()):
                answer += mp[Y]
            value *= 2
        if (preXor in mp .keys()):
            mp[preXor] += 1
        else:
            mp[preXor] = 1
    return answer


array = [2, 6, 7, 5, 8]
n = len(array)
print(findSubarray(array, n))

# Expected output:
6
# maximum xor of two numbers in an array | function to return the maximum xor ; calculating xor of each pair ; 
def max_xor(arr, n):
    maxXor = 0
    for i in range(n):
        for j in range(i + 1, n):
            maxXor = max(maxXor, arr[i] ^ arr[j])
    return maxXor


if __name__ == '__main__':
    arr = [25, 10, 2, 8, 5, 3]
    n = len(arr)
    print(max_xor(arr, n))

# Expected output:
28
# maximum xor of two numbers in an array | function to return the maximum xor ; set the i 'th bit in mask  like 100000, 110000, 111000.. ; just keep the prefix till i ' th ▁ bit ▁ neglecting ▁ all ▁ ▁ the ▁ bit ' s after i 'th bit ; find two pair in set such that a ^ b = newmaxx which is the highest possible bit can be obtained ; clear the set for next iteration ; 
def max_xor(arr, n):
    maxx = 0
    mask = 0
    se = set()
    for i in range(30, -1, -1):
        mask |= (1 << i)
        newMaxx = maxx | (1 << i)
        for i in range(n):
            se .add(arr[i] & mask)
        for prefix in se:
            if (newMaxx ^ prefix) in se:
                maxx = newMaxx
                break
        se .clear()
    return maxx


arr = [25, 10, 2, 8, 5, 3]
n = len(arr)
print(max_xor(arr, n))

# Expected output:
28
# count of triplets that satisfy the given equation | function to return the count of required triplets ; first element of the current sub - array ; xor every element of the current sub - array ; if the xor becomes 0 then update the count of triplets ; 
def CountTriplets(arr, n):
    ans = 0
    for i in range(n - 1):
        first = arr[i]
        for j in range(i + 1, n):
            first ^= arr[j]
            if (first == 0):
                ans += (j - i)
    return ans


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

# Expected output:
2
# find the majority element | set 3 ( bit magic ) |  ; number of bits in the integer ; variable to calculate majority element ; loop to iterate through all the bits of number ; loop to iterate through all elements in array to count the total set bit at position i from right ; if the total set bits exceeds n / 2 , this bit should be present in majority element . ; iterate through array get the count of candidate majority element ; verify if the count exceeds n / 2 ; 
def findMajority(arr, n):
    Len = 32
    number = 0
    for i in range(Len):
        count = 0
        for j in range(n):
            if (arr[j] & (1 << i)):
                count += 1
        if (count > (n // 2)):
            number += (1 << i)
    count = 0
    for i in range(n):
        if (arr[i] == number):
            count += 1
    if (count > (n // 2)):
        print(number)
    else:
        print("Majority Element Not Present")


arr = [3, 3, 4, 2, 4, 4, 2, 4, 4]
n = len(arr)
findMajority(arr, n)

# Expected output:
4
# count number of bits to be flipped to convert a to b | set | function to return the count of bits to be flipped to convert a to b ; to store the required count ; loop until both of them become zero ; store the last bits in a as well as b ; if the current bit is not same in both the integers ; right shift both the integers by 1 ; return the count ; 
def countBits(a, b):
    count = 0
    while (a or b):
        last_bit_a = a & 1
        last_bit_b = b & 1
        if (last_bit_a != last_bit_b):
            count += 1
        a = a >> 1
        b = b >> 1
    return count


a = 10
b = 7
print(countBits(a, b))

# Expected output:
3
# count set | recursive function to find number of set bist in a number ; base condition ; if least significant bit is set ; if least significant bit is not set ; 
def CountSetBits(n):
    if (n == 0):
        return 0
    if ((n & 1) == 1):
        return 1 + CountSetBits(n >> 1)
    else:
        return CountSetBits(n >> 1)


if __name__ == '__main__':
    n = 21
    print(CountSetBits(n))

# Expected output:
3
# count smaller elements on right side and greater elements on left side using binary index tree | python3 implementation of the approach ; function to return the sum of arr [ 0. . index ] this function assumes that the array is preprocessed and partial sums of array elements are stored in bitree [ ] ; initialize result ; traverse ancestors of bitree [ index ] ; add current element of bitree to sum ; move index to parent node in getsum view ; updates a node in binary index tree ( bitree ) at given index in bitree . the given value ' val ' is added to bitree [ i ] and all of its ancestors in tree . ; traverse all ancestors and add 'val ; add ' val ' to current node of bi tree ; update index to that of parent in update view ; converts an array to an array with values from 1 to n and relative order of smaller and greater elements remains same . for example , { 7 , - 90 , 100 , 1 } is converted to { 3 , 1 , 4 , 2 } ; create a copy of arrp [ ] in temp and sort the temp array in increasing order ; traverse all array elements ; lower_bound ( ) returns pointer to the first element greater than or equal to arr [ i ] ; function to find smaller_right array ; convert arr [ ] to an array with values from 1 to n and relative order of smaller and greater elements remains same . for example , { 7 , - 90 , 100 , 1 } is converted to { 3 , 1 , 4 , 2 } ; create a bit with size equal to maxelement + 1 ( extra one is used so that elements can be directly be used as index ) ; to store smaller elements in right side and greater elements on left side ; traverse all elements from right . ; get count of elements smaller than arr [ i ] ; add current element to bit ; print smaller_right array ; find all left side greater elements ; get count of elements greater than arr [ i ] ; add current element to bit ; print greater_left array ; 

from bisect import bisect_left as lower_bound


def getSum(BITree, index):
    s = 0
    while index > 0:
        s += BITree[index]
        index -= index & (-index)
    return s


def updateBIT(BITree, n, index, val):
    while index <= n:
        BITree[index] += val
        index += index & (-index)


def convert(arr, n):
    temp = [0] * n
    for i in range(n):
        temp[i] = arr[i]
    temp .sort()
    for i in range(n):
        arr[i] = lower_bound(temp, arr[i]) + 1


def findElements(arr, n):
    convert(arr, n)
    BIT = [0] * (n + 1)
    smaller_right = [0] * n
    greater_left = [0] * n
    for i in range(n - 1, -1, -1):
        smaller_right[i] = getSum(BIT, arr[i] - 1)
        updateBIT(BIT, n, arr[i], 1)
    print("Smaller right:", end=" ")
    for i in range(n):
        print(smaller_right[i], end=" ")
    print()
    for i in range(1, n + 1):
        BIT[i] = 0
    for i in range(n):
        greater_left[i] = i - getSum(BIT, arr[i])
        updateBIT(BIT, n, arr[i], 1)
    print("Greater left:", end=" ")
    for i in range(n):
        print(greater_left[i], end=" ")
    print()


if __name__ == "__main__":
    arr = [12, 1, 2, 3, 0, 11, 4]
    n = len(arr)
    findElements(arr, n)

# Expected output:
Smaller right: 6 1 1 1 0 1 0 
Greater left: 0 1 1 1 4 1 2
# sum of bitwise or of all pairs in a given array | returns value of " arr [ 0 ] ▁ | ▁ arr [ 1 ] ▁ + ▁ arr [ 0 ] ▁ | ▁ arr [ 2 ] ▁ + ▁ . . . ▁ arr [ i ] ▁ | ▁ arr [ j ] ▁ + ▁ . . . . . ▁ arr [ n - 2 ] ▁ | ▁ arr [ n - 1 ] " ; consider all pairs ( arr [ i ] , arr [ j ) such that i < j ; 
def pairORSum(arr, n):
    ans = 0
    for i in range(0, n):
        for j in range((i + 1), n):
            ans = ans + arr[i] | arr[j]
    return ans


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

# Expected output:
28
# number of 0 s and 1 s at prime positions in the given array | function that returns true if n is prime ; check from 2 to n ; function to find the count of 0 s and 1 s at prime indices ; to store the count of 0 s and 1 s ; if current 0 is at prime position ; if current 1 is at prime position ; 
def isPrime(n):
    if (n <= 1):
        return False
    for i in range(2, n):
        if (n % i == 0):
            return False
    return True


def countPrimePosition(arr):
    c0 = 0
    c1 = 0
    n = len(arr)
    for i in range(n):
        if (arr[i] == 0 and isPrime(i)):
            c0 += 1
        if (arr[i] == 1 and isPrime(i)):
            c1 += 1
    print("Number of 0s =", c0)
    print("Number of 1s =", c1)


if __name__ == "__main__":
    arr = [1, 0, 1, 0, 1]
    countPrimePosition(arr)

# Expected output:
Number of 0s = 1
Number of 1s = 1
# multiply a number by 15 without using * and / operators | function to return ( 15 * n ) without using ' * ' or ' / ' operator ; prod = 16 * n ; ( ( 16 * n ) - n ) = 15 * n ; 
def multiplyByFifteen(n):
    prod = (n << 4)
    prod = prod - n
    return prod


n = 7
print(multiplyByFifteen(n))

# Expected output:
105
# multiply a number by 15 without using * and / operators | function to perform multiplication ; prod = 8 * n ; add ( 4 * n ) ; add ( 2 * n ) ; add n ; ( 8 * n ) + ( 4 * n ) + ( 2 * n ) + n = ( 15 * n ) ; 
def multiplyByFifteen(n):
    prod = (n << 3)
    prod += (n << 2)
    prod += (n << 1)
    prod += n
    return prod


n = 7
print(multiplyByFifteen(n))

# Expected output:
105
# minimum value among and of elements of every subset of an array | python program for the above approach ; find and of whole array ; print the answer ; 
def minAND(arr, n):
    s = arr[0]
    for i in range(1, n):
        s = s & arr[i]
    print(s)


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

# Expected output:
0
# modify a binary array to bitwise and of all elements as 1 | function to check if it is possible or not ; 
def check(a, n):
    for i in range(n):
        if (a[i]):
            return True
    return False


if __name__ == '__main__':
    a = [0, 1, 0, 1]
    n = len(a)
    if (check(a, n)):
        print("YES")
    else:
        print("NO")

# Expected output:
YES
# find array using different xors of elements in groups of size 4 | utility function to print the contents of the array ; function to find the required array ; print the array ; 
def printArray(arr, n):
    for i in range(n):
        print(arr[i], end=" ")


def findArray(q, n):
    arr = [None] * n
    k = 0
    for j in range(int(n / 4)):
        ans = q[k] ^ q[k + 3]
        arr[k + 1] = q[k + 1] ^ ans
        arr[k + 2] = q[k + 2] ^ ans
        arr[k] = q[k] ^ ((arr[k + 1]) ^ (arr[k + 2]))
        arr[k + 3] = q[k + 3] ^ (arr[k + 1] ^ arr[k + 2])
        k += 4
    printArray(arr, n)


if __name__ == '__main__':
    q = [4, 1, 7, 0]
    n = len(q)
    findArray(q, n)

# Expected output:
2 5 3 6
# count of values of x <= n for which ( n xor x ) = ( n | function to return the count of valid values of x ; convert n into binary string ; to store the count of 1 s ; if current bit is 1 ; calculating answer ; 
def countX(n):
    binary = "{0:b}".format(n)
    count = 0
    for i in range(len(binary)):
        if (binary[i] == '1'):
            count += 1
    answer = int(pow(2, count))
    return answer


if __name__ == "__main__":
    n = 5
    answer = countX(n)
    print(answer)

# Expected output:
4
# check if the binary representation of a number has equal number of 0 s and 1 s in blocks | function to convert decimal to binary ; count same bits in last block ; if n is 0 or it has all 1 s , then it is not considered to have equal number of 0 s and 1 s in blocks . ; count same bits in all remaining blocks . ; 
def isEqualBlock(n):
    first_bit = n % 2
    first_count = 1
    n = n // 2
    while n % 2 == first_bit and n > 0:
        n = n // 2
        first_count += 1
    if n == 0:
        return False
    while n > 0:
        first_bit = n % 2
        curr_count = 1
        n = n // 2
        while n % 2 == first_bit:
            n = n // 2
            curr_count += 1
        if curr_count != first_count:
            return False
    return True


if __name__ == "__main__":
    n = 51
    if isEqualBlock(n):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# first and last three bits | python 3 implementation of the approach ; function to print the first and last 3 bits equivalent decimal number ; converting n to binary ; length of the array has to be at least 3 ; convert first three bits to decimal ; print the decimal ; convert last three bits to decimal ; print the decimal ; 

from math import pow


def binToDecimal3(n):
    a = [0 for i in range(64)]
    x = 0
    i = 0
    while (n > 0):
        a[i] = n % 2
        n = int(n / 2)
        i += 1
    if (i < 3):
        x = 3
    else:
        x = i
    d = 0
    p = 0
    for i in range(x - 3, x, 1):
        d += a[i] * pow(2, p)
        p += 1
    print(int(d), end=" ")
    d = 0
    p = 0
    for i in range(0, 3, 1):
        d += a[i] * pow(2, p)
        p += 1
    print(int(d), end=" ")


if __name__ == '__main__':
    n = 86
    binToDecimal3(n)

# Expected output:
5 6
# first and last three bits | function to print the first and last 3 bits equivalent decimal number ; number formed from last three bits ; let us get first three bits in n ; number formed from first three bits ; printing result ; 
def binToDecimal3(n):
    last_3 = ((n & 4) + (n & 2) + (n & 1))
    n = n >> 3
    while (n > 7):
        n = n >> 1
    first_3 = ((n & 4) + (n & 2) + (n & 1))
    print(first_3, last_3)


if __name__ == "__main__":
    n = 86
    binToDecimal3(n)

# Expected output:
5 6
# count of numbers which can be made power of 2 by given operation | function that returns true if x is a power of 2 ; if x & ( x - 1 ) = 0 then x is a power of 2 ; function to return the required count ; if a [ i ] or ( a [ i ] + 1 ) is a power of 2 ; 
def isPowerOfTwo(x):
    if (x == 0):
        return False
    if ((x & (x - 1)) == 0):
        return True
    else:
        return False


def countNum(a, n):
    count = 0
    for i in range(0, n, 1):
        if (isPowerOfTwo(a[i]) or isPowerOfTwo(a[i] + 1)):
            count += 1
    return count


if __name__ == '__main__':
    arr = [5, 6, 9, 3, 1]
    n = len(arr)
    print(countNum(arr, n))

# Expected output:
2
# sum of elements from an array having even parity | function that returns true if x has even parity ; we basically count set bits https : www . geeksforgeeks . org / count - set - bits - in - an - integer / ; function to return the sum of the elements from an array which have even parity ; if a [ i ] has even parity ; 
def checkEvenParity(x):
    parity = 0
    while (x != 0):
        x = x & (x - 1)
        parity += 1
    if (parity % 2 == 0):
        return True
    else:
        return False


def sumlist(a, n):
    sum = 0
    for i in range(n):
        if (checkEvenParity(a[i])):
            sum += a[i]
    return sum


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

# Expected output:
17
# range sum queries and update with square root | python program to calculate sum in an interval and update with square root ; maximum size of input array ; structure for queries with members type , leftindex , rightindex of the query ; function for updating the value ; function for calculating the required sum between two indexes ; function to return answer to queries ; declaring a set ; inserting indexes of those numbers which are greater than 1 ; update query ; find the left index of query in the set using binary search auto it = s . lower_bound ( que [ i ] . l ) ; ; if it crosses the right index of query or end of set , then break ; update the value of arr [ i ] to itss square root ; if updated value becomes equal to 1 remove it from the set ; increment the index ; sum query ; 

from typing import List
import bisect
from math import sqrt, floor
MAX = 100
BIT = [0 for _ in range(MAX + 1)]


class queries:
    def __init__(self, type: int = 0, l: int = 0, r: int = 0) -> None:
        self .type = type
        self .l = l
        self .r = r


def update(x: int, val: int, n: int) -> None:
    a = x
    while a <= n:
        BIT[a] += val
        a += a & -a


def sum(x: int) -> int:
    s = 0
    a = x
    while a:
        s += BIT[a]
        a -= a & -a
    return s


def answerQueries(arr: List[int], que: List[queries], n: int, q: int) -> None:
    s = set()
    for i in range(1, n):
        if (arr[i] > 1):
            s .add(i)
        update(i, arr[i], n)
    for i in range(q):
        if (que[i].type == 1):
            while True:
                ss = list(sorted(s))
                it = bisect .bisect_left(ss, que[i].l)
                if it == len(s) or ss[it] > que[i].r:
                    break
                que[i].l = ss[it]
                update(ss[it], floor(sqrt(arr[ss[it]]) - arr[ss[it]]), n)
                arr[ss[it]] = floor(sqrt(arr[ss[it]]))
                if (arr[ss[it]] == 1):
                    s .remove(ss[it])
                que[i].l += 1
        else:
            print(sum(que[i].r) - sum(que[i].l - 1))


if __name__ == "__main__":
    q = 4
    arr = [0, 4, 5, 1, 2, 4]
    n = len(arr)
    que = [queries()for _ in range(q + 1)]
    que[0].type, que[0].l, que[0].r = 2, 1, 5
    que[1].type, que[1].l, que[1].r = 1, 1, 2
    que[2].type, que[2].l, que[2].r = 1, 2, 4
    que[3].type, que[3].l, que[3].r = 2, 1, 5
    answerQueries(arr, que, n, q)

# Expected output:
16
9
# count pairs with bitwise xor as even number | function to count number of even pairs ; variable for counting even pairs ; find all pairs ; find xor operation check even or even ; return number of even pair ; 
def findevenPair(A, N):
    evenPair = 0
    for i in range(0, N):
        for j in range(i + 1, N):
            if ((A[i] ^ A[j]) % 2 == 0):
                evenPair += 1
    return evenPair


def main():
    A = [5, 4, 7, 2, 1]
    N = len(A)
    print(findevenPair(A, N))


if __name__ == '__main__':
    main()

# Expected output:
4
# count pairs with bitwise xor as even number | function to count number of even pairs ; find all pairs ; return number of even pair ; 
def findEvenPair(A, N):
    count = 0
    for i in range(0, N):
        if (A[i] % 2 != 0):
            count += 1
    totalPairs = (N * (N - 1) / 2)
    oddEvenPairs = count * (N - count)
    return (int)(totalPairs - oddEvenPairs)


def main():
    a = [5, 4, 7, 2, 1]
    n = len(a)
    print(findEvenPair(a, n))


if __name__ == '__main__':
    main()

# Expected output:
4
# count pairs with bitwise | function to count number of pairs even bitwise and ; variable for counting even pairs ; find all pairs ; find and operation to check evenpair ; return number of even pair ; 
def findevenPair(A, N):
    evenPair = 0
    for i in range(0, N):
        for j in range(i + 1, N):
            if ((A[i] & A[j]) % 2 == 0):
                evenPair += 1
    return evenPair


a = [5, 1, 3, 2]
n = len(a)
print(findevenPair(a, n))

# Expected output:
3
# count pairs with bitwise | function to count number of pairs with even bitwise and ; count odd numbers ; count odd pairs ; return number of even pair ; 
def findevenPair(A, N):
    count = 0
    for i in range(0, N):
        if (A[i] % 2 != 0):
            count += 1
    oddCount = count * (count - 1) / 2
    return (int)((N * (N - 1) / 2) - oddCount)


a = [5, 1, 3, 2]
n = len(a)
print(findevenPair(a, n))

# Expected output:
3
# find a value whose xor with given number is maximum | function to calculate answer ; find number of bits in the given integer ; xor the given integer with poe ( 2 , number_of_bits - 1 and print the result ; 
def calculate(X):
    number_of_bits = 8
    return ((1 << number_of_bits) - 1) ^ X


if __name__ == "__main__":
    X = 4
    print("Required Number is:", calculate(X))

# Expected output:
Required Number is: 251
# xor of all elements of array with set bits equal to k | function to find xor of desired elements ; initialize vector ; push required elements ; initialize result with first element of vector ; 
def xorGivenSetBits(arr, n, k):
    v = []
    for i in range(0, n, 1):
        if (bin(arr[i]).count('1') == k):
            v .append(arr[i])
    result = v[0]
    for i in range(1, len(v), 1):
        result = result ^ v[i]
    return result


if __name__ == '__main__':
    arr = [2, 13, 1, 19, 7]
    n = len(arr)
    k = 3
    print(xorGivenSetBits(arr, n, k))

# Expected output:
25
# replace every element of the array with bitwise xor of all other | function to replace the elements ; calculate the xor of all the elements ; replace every element by the xor of all other elements ; 
def ReplaceElements(arr, n):
    X = 0
    for i in range(n):
        X ^= arr[i]
    for i in range(n):
        arr[i] = X ^ arr[i]


if __name__ == "__main__":
    arr = [2, 3, 3, 5, 5]
    n = len(arr)
    ReplaceElements(arr, n)
    for i in range(n):
        print(arr[i], end=" ")

# Expected output:
0 1 1 7 7