giulio98/xlcost-single-prompt huggingface dataset:
# assign other value to a variable from two possible values | function to alternate the values ; 
def alternate(a, b, x):
    x = a ^ b ^ x
    print("After exchange")
    print("x is", x)


a = -10
b = 15
x = a
print("x is", x)
alternate(a, b, x)

# Expected output:
x is -10
After exchange
x is 15
# number of leading zeros in binary representation of a given number | function to count the no . of leading zeros ; keep shifting x by one until leftmost bit does not become 1. ; 
def countZeros(x):
    total_bits = 32
    res = 0
    while ((x & (1 << (total_bits - 1))) == 0):
        x = (x << 1)
        res += 1
    return res


x = 101
print(countZeros(x))

# Expected output:
25
# number of leading zeros in binary representation of a 
def countZeros(x):
    n = 32
    y = x >> 16
    if (y != 0):
        n = n - 16
        x = y
    y = x >> 8
    if (y != 0):
        n = n - 8
        x = y
    y = x >> 4
    if (y != 0):
        n = n - 4
        x = y
    y = x >> 2
    if (y != 0):
        n = n - 2
        x = y
    y = x >> 1
    if (y != 0):
        return n - 2
    return n - x


def main():
    x = 101
    print(countZeros(x))


if __name__ == '__main__':
    main()

# Expected output:
25
# comparing leading zeros in binary representations of two numbers | function to compare the no . of leading zeros ; if both have same no . of leading zeros ; if y has more leading zeros ; 
def LeadingZeros(x, y):
    if ((x ^ y) <= (x & y)):
        print("Equal")
    elif ((x & (~y)) > y):
        print(y)
    else:
        print(x)


if __name__ == '__main__':
    x = 10
    y = 16
    LeadingZeros(x, y)

# Expected output:
10
# printing all subsets of { 1 , 2 , 3 , ... n } without using array or loop | this recursive function calls subset function to print the subsets one by one . numbits -- > number of bits needed to represent the number ( simply input value n ) . num -- > initially equal to 2 ^ n - 1 and decreases by 1 every recursion until 0. ; print the subset corresponding to binary representation of num . ; call the function recursively to print the next subset . ; this function recursively prints the subset corresponding to the binary representation of num . nthbit -- > nth bit from right side starting from n and decreases until 0. ; print number in given subset only if the bit corresponding to it is set in num . ; check for the next bit ; 
def subset(nthBit, num, numOfBits):
    if nthBit >= 0:
        if num & (1 << nthBit) != 0:
            print(numOfBits - nthBit, end=" ")
        subset(nthBit - 1, num, numOfBits)
    else:
        return


def printSubsets(numOfBits, num):
    if num >= 0:
        print("{", end=" ")
        subset(numOfBits - 1, num, numOfBits)
        print("}")
        printSubsets(numOfBits, num - 1)
    else:
        return


n = 4
printSubsets(n, 2 ** n - 1)

# Expected output:
{ 1 2 3 4 }
{ 1 2 3 }
{ 1 2 4 }
{ 1 2 }
{ 1 3 4 }
{ 1 3 }
{ 1 4 }
{ 1 }
{ 2 3 4 }
{ 2 3 }
{ 2 4 }
{ 2 }
{ 3 4 }
{ 3 }
{ 4 }
{ }
# number of mismatching bits in the binary representation of two integers | compute number of different bits ; since , the numbers are less than 2 ^ 31 run the loop from '0' to '31' only ; right shift both the numbers by ' i ' and check if the bit at the 0 th position is different ; 
def solve(A, B):
    count = 0
    for i in range(0, 32):
        if (((A >> i) & 1) != ((B >> i) & 1)):
            count = count + 1
    print("Number of different bits :", count)


A = 12
B = 15
solve(A, B)

# Expected output:
Number of different bits : 2
# set the rightmost off bit | python3 program to set the rightmost unset bit ; if all bits are set ; set rightmost 0 bit ; 
def setRightmostUnsetBit(n):
    if n & (n + 1) == 0:
        return n
    return n | (n + 1)


if __name__ == "__main__":
    n = 21
    print(setRightmostUnsetBit(n))

# Expected output:
23
# find bitwise and ( & ) of all possible sub | function to return and of sub - arrays ; 
def AND(a, n):
    ans = a[0]
    for i in range(n):
        ans &= a[i]
    return ans


if __name__ == "__main__":
    a = [1, 2, 3]
    n = len(a)
    print(AND(a, n))

# Expected output:
0
# 2 's complement for a givin string using xor | python program to find 2 's complement using xor. ; a flag used to find if a 1 bit is seen or not . ; xor operator is used to flip the ; bits after converting in to ascii values ; if there is no 1 in the string so just add 1 in starting of string and return ; 
def TwoscomplementbyXOR(str):
    n = len(str)
    check_bit = 0
    i = n - 1
    s = list(str)
    while (i >= 0):
        if (s[i] == '0' and check_bit == 0):
            continue
        else:
            if (check_bit == 1):
                s[i] = chr((ord(s[i]) - 48) ^ 1 + 48)
            check_bit = 1
        i -= 1
    str = "".join(s)
    if (check_bit == 0):
        return "1" + str
    else:
        return str


str = "101"
print(TwoscomplementbyXOR(str))

# Expected output:
011
# check whether bits are in alternate pattern in the given range | set | function to check whether rightmost kth bit is set or not in 'n ; function to set the rightmost kth bit in 'n ; kth bit of n is being set by this operation ; function to check if all the bits are set or not in the binary representation of 'n ; if true , then all bits are set ; else all bits are not set ; function to check if a number has bits in alternate pattern ; to check if all bits are set in 'num ; function to check whether bits are in alternate pattern in the given range ; preparing a number ' num ' and ' left _ shift ' which can be further used for the check of alternate pattern in the given range ; unset all the bits which are left to the rth bit of ( r + 1 ) th bit ; right shift ' num ' by ( l - 1 ) bits ; 
def isKthBitSet(n, k):
    if ((n >> (k - 1)) & 1):
        return True
    return False


def setKthBit(n, k):
    return ((1 << (k - 1)) | n)


def allBitsAreSet(n):
    if (((n + 1) & n) == 0):
        return True
    return False


def bitsAreInAltOrder(n):
    num = n ^ (n >> 1)
    return allBitsAreSet(num)


def bitsAreInAltPatrnInGivenRange(n, l, r):
    if (isKthBitSet(n, r)):
        num = n
        left_shift = r

    else:
        num = setKthBit(n, (r + 1))
        left_shift = r + 1
    num = num & ((1 << left_shift) - 1)
    num = num >> (l - 1)

    return bitsAreInAltOrder(num)


if __name__ == '__main__':
    n = 18
    l = 1
    r = 3
    if (bitsAreInAltPatrnInGivenRange(n, l, r)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# increment a number without using ++ or + | function that increment the value . ; invert bits and apply negative sign ; 
def increment(i):
    i = -(~i)
    return i


if __name__ == "__main__":
    n = 3
    print(increment(n))

# Expected output:
4
# maximum sum by adding numbers with same number of set bits | count the number of bits for each element of array ; count the number of set bits ; function to return the the maximum sum ; calculate the ; assuming the number to be a maximum of 32 bits ; add the number to the number of set bits ; find the maximum sum ; 
def bit_count(n):
    count = 0
    while (n > 0):
        count += 1
        n = n & (n - 1)
    return count


def maxsum(arr, n):
    bits = [0] * n
    for i in range(n):
        bits[i] = bit_count(arr[i])
    sum = [0] * 32
    for i in range(n):
        sum[bits[i]] += arr[i]
    maximum = 0
    for i in range(32):
        maximum = max(sum[i], maximum)
    return maximum


arr = [2, 3, 8, 5, 6, 7]
n = len(arr)
print(maxsum(arr, n))

# Expected output:
14
# sum of xor of sum of all pairs in an array | python3 program to find xor of pair sums . ; 
def xor_pair_sum(ar, n):
    total = 0
    for i in range(n):
        total = total ^ ar[i]
    return 2 * total


if __name__ == "__main__":
    data = [1, 2, 3]
    print(xor_pair_sum(data, len(data)))

# Expected output:
0
# count pairs with bitwise or as even number | python 3 program to count pairs with even or ; count total even numbers in array . ; return count of even pair ; 
def findEvenPair(A, N):
    count = 0
    for i in range(N):
        if (not (A[i] & 1)):
            count += 1
    return count * (count - 1) // 2


if __name__ == "__main__":
    A = [5, 6, 2, 8]
    N = len(A)
    print(findEvenPair(A, N))

# Expected output:
3
# check whether all the bits are unset in the given range | function to check whether all the bits are unset in the given range or not ; calculating a number ' num ' having ' r ' number of bits and bits in the range l to r are the only set bits ; new number which could only have one or more set bits in the range l to r and nowhere else ; if true , then all bits are unset in the given range ; else all bits are not unset in the given range ; 
def allBitsSetInTheGivenRange(n, l, r):
    num = (((1 << r) - 1) ^ ((1 << (l - 1)) - 1))
    new_num = n & num
    if (new_num == 0):
        return True
    return false


n = 17
l = 2
r = 4
if (allBitsSetInTheGivenRange(n, l, r)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# check if a number has same number of set and unset bits | function to check if a number has same setbits and unset bits ; iterate for all bits of a number ; if set ; if unset ; right shift number by 1 ; is number of set bits are equal to unset bits ; 
def checkSame(n):
    set, unset = 0, 0
    while (n):
        if (n and 1):
            set + 1
        else:
            unset += 1
        n = n >> 1
    if (set == unset):
        return True
    else:
        return False


if __name__ == '__main__':
    n = 12
    if (checkSame(n)):
        print("YES")
    else:
        print("NO")

# Expected output:
YES
# check if concatenation of two strings is balanced or not | check if given string is balanced bracket sequence or not . ; if current bracket is an opening bracket push it to stack . ; if current bracket is a closing bracket then pop from stack if it is not empty . if stack is empty then sequence is not balanced . ; if stack is not empty , then sequence is not balanced . ; function to check if string obtained by concatenating two bracket sequences is balanced or not . ; check if s1 + s2 is balanced or not . ; check if s2 + s1 is balanced or not . ; 
def isBalanced(s):
    st = list()
    n = len(s)
    for i in range(n):
        if s[i] == '(':
            st .append(s[i])
        else:
            if len(st) == 0:
                return False
            else:
                st .pop()
    if len(st) > 0:
        return False
    return True


def isBalancedSeq(s1, s2):
    if (isBalanced(s1 + s2)):
        return True
    return isBalanced(s2 + s1)


if __name__ == "__main__":
    s1 = ")()(())))"
    s2 = "(()(()("
    if isBalancedSeq(s1, s2):
        print("Balanced")
    else:
        print("Not Balanced")

# Expected output:
Balanced
# find iâ €™ th index character in a binary string obtained after n iterations | set 2 | function to find the i - th character ; distance between two consecutive elements after n iterations ; binary representation of m ; kth digit will be derived from root for sure ; check whether there is need to flip root or not ; 
def KthCharacter(m, n, k):
    distance = pow(2, n)
    Block_number = int(k / distance)
    remaining = k % distance
    s = [0] * 32
    x = 0
    while (m > 0):
        s[x] = m % 2
        m = int(m / 2)
        x += 1
    root = s[x - 1 - Block_number]
    if (remaining == 0):
        print(root)
        return
    flip = True
    while (remaining > 1):
        if (remaining & 1):
            flip = not (flip)
        remaining = remaining >> 1
    if (flip):
        print(not (root))
    else:
        print(root)


m = 5
k = 5
n = 3
KthCharacter(m, n, k)

# Expected output:
1
# check whether the number has only first and last bits set | set 2 | function to check whether the number has only first and last bits set ; 
def onlyFirstAndLastAreSet(n):
    if (n == 1):
        return True
    if (n == 2):
        return False
    return (((n - 1) & (n - 2)) == 0)


n = 9
if (onlyFirstAndLastAreSet(n)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# number with set bits only between l | python 3 program to print the integer with all the bits set in range l - r naive approach ; function to return the integer with all the bits set in range l - r ; iterate from l to r and add all powers of 2 ; 

from math import pow


def getInteger(L, R):
    number = 0
    for i in range(L, R + 1, 1):
        number += pow(2, i)
    return number


if __name__ == '__main__':
    L = 2
    R = 5
    print(int(getInteger(L, R)))

# Expected output:
60
# number with set bits only between l | function to return the integer with all the bits set in range l - r ; 
def setbitsfromLtoR(L, R):
    return ((1 << (R + 1)) - (1 << L))


L = 2
R = 5
print(setbitsfromLtoR(L, R))

# Expected output:
60
# xor of sum of every possible pair of an array | function to find xor of sum of all pairs ; calculate xor of all the elements ; return twice of xor value ; 
def findXor(arr, n):
    xoR = 0
    for i in range(0, n):
        xoR = xoR ^ arr[i]
    return xoR * 2


arr = [1, 5, 6]
n = len(arr)
print(findXor(arr, n))

# Expected output:
4
# largest set with bitwise or equal to n | function to find the largest set with bitwise or equal to n ; if the bitwise or of n and i is equal to n , then include i in the set ; 
def setBitwiseORk(n):
    v = []
    for i in range(0, n + 1, 1):
        if ((i | n) == n):
            v .append(i)
    for i in range(0, len(v), 1):
        print(v[i], end=' ')


if __name__ == '__main__':
    n = 5
    setBitwiseORk(n)

# Expected output:
0 1 4 5
# two odd occurring elements in an array where all other occur even times | python 3 code to find two odd occurring elements in an array where all other elements appear even number of times . ; find xor of all numbers ; find a set bit in the xor ( we find rightmost set bit here ) ; traverse through all numbers and divide them in two groups ( i ) having set bit set at same position as the only set bit in set_bit ( ii ) having 0 bit at same position as the only set bit in set_bit ; xor of two different sets are our required numbers . ; 
def printOdds(arr, n):
    res = 0
    for i in range(0, n):
        res = res ^ arr[i]
    set_bit = res & (~(res - 1))
    x = 0
    y = 0
    for i in range(0, n):
        if (arr[i] & set_bit):
            x = x ^ arr[i]
        else:
            y = y ^ arr[i]
    print(x, y, end="")


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

# Expected output:
5 2
# maximum subset with bitwise or equal to k | function to find the maximum subset with bitwise or equal to k ; if the bitwise or of k and element is equal to k , then include that element in the subset ; store the bitwise or of elements in v ; if ans is not equal to k , subset doesn 't exist ; 
def subsetBitwiseORk(arr, n, k):
    v = []
    for i in range(0, n):
        if ((arr[i] | k) == k):
            v .append(arr[i])
    ans = 0
    for i in range(0, len(v)):
        ans |= v[i]
    if (ans != k):
        print("Subsetdoesnotexist")
        return
    for i in range(0, len(v)):
        print("{} ".format(v[i]), end="")


k = 3
arr = [1, 4, 2]
n = len(arr)
subsetBitwiseORk(arr, n, k)

# Expected output:
1 2
# number whose xor sum with given array is a given number k | this function returns the number to be inserted in the given array ; initialise the answer with k ; ans ^= a [ i ] xor of all elements in the array ; 
def findEletobeInserted(A, n, k):
    ans = k
    for i in range(n):
        ans ^= A[i]
    return ans


if __name__ == '__main__':
    A = [1, 2, 3, 4, 5]
    n = len(A)
    k = 10
    print(
        findEletobeInserted(
            A,
            n,
            k),
        "has to be inserted in the given",
        "array to make xor sum of",
        k)

# Expected output:
11 has to be inserted in the given array to make xor sum of 10
# generate n | function to convert decimal to binary ; leftmost digits are filled with 0 ; function to generate gray code ; generate gray code of corresponding binary number of integer i . ; printing gray code ; 
def decimalToBinaryNumber(x, n):
    binaryNumber = [0] * x
    i = 0
    while (x > 0):
        binaryNumber[i] = x % 2
        x = x // 2
        i += 1
    for j in range(0, n - i):
        print('0', end="")
    for j in range(i - 1, -1, -1):
        print(binaryNumber[j], end="")


def generateGrayarr(n):
    N = 1 << n
    for i in range(N):
        x = i ^ (i >> 1)
        decimalToBinaryNumber(x, n)
        print()


if __name__ == '__main__':
    n = 3
    generateGrayarr(n)

# Expected output:
000
001
011
010
110
111
101
100
# sum of bitwise and of all possible subsets of given set | python3 program to calculate sum of bit - wise and sum of all subsets of an array ; assuming representation of each element is in 32 bit ; iterating array element ; counting the set bit of array in ith position ; counting subset which produce sum when particular bit position is set . ; multiplying every position subset with 2 ^ i to count the sum . ; 

BITS = 32


def andSum(arr, n):
    ans = 0
    for i in range(0, BITS):
        countSetBits = 0
        for j in range(0, n):
            if (arr[j] & (1 << i)):
                countSetBits = (countSetBits + 1)
        subset = ((1 << countSetBits) - 1)
        subset = (subset * (1 << i))
        ans = ans + subset
    return ans


arr = [1, 2, 3]
size = len(arr)
print(andSum(arr, size))

# Expected output:
9
# maximize the number by rearranging bits | an efficient python3 program to find minimum number formed by bits of a given number . ; returns maximum number formed by bits of a given number . ; _popcnt32 ( a ) gives number of 1 's  present in binary representation of a. ; if all 32 bits are set . ; find a number witn n least significant set bits . ; now shift result by 32 - n ; 
def _popcnt32(n):
    count = 0
    while (n != 0):
        n = n & (n - 1)
        count = count + 1
    return count


def maximize(a):
    n = _popcnt32(a)
    if (n == 32):
        return a
    res = (1 << n) - 1
    return (res << (32 - n))


if __name__ == '__main__':
    a = 3
    print(maximize(a))

# Expected output:
3221225472
# minimum number using set bits of a given number | returns minimum number formed by bits of a given number . ; _popcnt32 ( a ) gives number of 1 's  present in binary representation  of a. ; 
def minimize(a):
    n = bin(a).count("1")
    return (pow(2, n) - 1)


a = 11
print(minimize(a))

# Expected output:
7
# maximum steps to transform 0 to x with bitwise and | function to get no of set bits in binary representation of positive integer n ; 
def countSetBits(n):
    count = 0
    while (n):
        count += n & 1
        n >>= 1
    return count


i = 3
print(countSetBits(i))

# Expected output:
2
# check a number is odd or even without modulus operator | returns true if n is even , else odd ; 
def isEven(n):
    isEven = True
    for i in range(1, n + 1):
        if isEven:
            isEven = False
        else:
            isEven = True
    return isEven


n = 101
if isEven(n):
    print("Even")
else:
    print("Odd")

# Expected output:
Odd
# check a number is odd or even without modulus operator | returns true if n is even , else odd ; return true if n / 2 does not result in a float value . ; 
def isEven(n):
    return (int(n / 2) * 2 == n)


n = 101
if (isEven(n)):
    print("Even")
else:
    print("Odd")

# Expected output:
Odd
# bitwise recursive addition of two integers | python program to do recursive addition of two integers ; if bitwise & is 0 , then there is not going to be any carry . hence result of xor is addition . ; 
def add(x, y):
    keep = (x & y) << 1
    res = x ^ y
    if (keep == 0):
        return res
    return add(keep, res)


print(add(15, 38))

# Expected output:
53
# count pairs in an array which have at least one digit common | returns true if the pair is valid , otherwise false ; converting integers to strings ; iterate over the strings and check if a character in first string is also present in second string , return true ; no common digit found ; returns the number of valid pairs ; iterate over all possible pairs ; 
def checkValidPair(num1, num2):
    s1 = str(num1)
    s2 = str(num2)
    for i in range(len(s1)):
        for j in range(len(s2)):
            if (s1[i] == s2[j]):
                return True
    return False


def countPairs(arr, n):
    numberOfPairs = 0
    for i in range(n):
        for j in range(i + 1, n):
            if (checkValidPair(arr[i], arr[j])):
                numberOfPairs += 1
    return numberOfPairs


if __name__ == "__main__":
    arr = [10, 12, 24]
    n = len(arr)
    print(countPairs(arr, n))

# Expected output:
2
# check if bitwise and of any subset is power of two | python3 program to check if bitwise and of any subset is power of two ; check for power of 2 or not ; check if there exist a subset whose bitwise and is power of 2. ; if there is only one element in the set . ; finding a number with all bit sets . ; check all the positions at which the bit is set . ; include all those elements whose i - th bit is set ; check for the set contains elements make a power of 2 or not ; 

NUM_BITS = 32


def isPowerOf2(num):
    return (num and (num & (num - 1)) == 0)


def checkSubsequence(arr, n):
    if (n == 1):
        return isPowerOf2(arr[0])
    total = 0
    for i in range(0, NUM_BITS):
        total = total | (1 << i)
    for i in range(0, NUM_BITS):
        ans = total
        for j in range(0, n):
            if (arr[j] & (1 << i)):
                ans = ans & arr[j]
        if (isPowerOf2(ans)):
            return True
    return False


arr = [12, 13, 7]
n = len(arr)
if (checkSubsequence(arr, n)):
    print("YES")
else:
    print("NO")

# Expected output:
YES
# levelwise alternating or and xor operations in segment tree | python3 program to build levelwise or / xor alternating segment tree ; a utility function to get the middle index from corner indexes . ; a recursive function that constructs segment tree for array [ ss . . se ] . ' si ' is index of current node in segment tree ' st ' , operation denotes which operation is carried out at that level to merge the left and right child . it 's either 0 or 1. ; if there is one element in array , store it in current node of segment tree and return ; if there are more than one elements , then recur for left and right subtrees and store the sum of values in this node ; build the left and the right subtrees by using the fact that operation at level ( i + 1 ) = ! ( operation at level i ) ; merge the left and right subtrees by checking the operation to be carried . if operation = 1 , then do or else xor ; or operation ; xor operation ; function to construct segment tree from given array . this function allocates memory for segment tree and calls constructstutil ( ) to fill the allocated memory ; height of segment tree ; maximum size of segment tree ; allocate memory ; operation = 1 ( xor ) if height of tree is even else it is 0 ( or ) for the root node ; fill the allocated memory st ; return the constructed segment tree ; 

import math


def getMid(s, e):
    return s + (e - s) // 2


def constructSTUtil(arr, ss, se, st, si, operation):
    if (ss == se):
        st[si] = arr[ss]
        return
    mid = getMid(ss, se)
    constructSTUtil(arr, ss, mid, st, si * 2 + 1, not operation)
    constructSTUtil(arr, mid + 1, se, st, si * 2 + 2, not operation)
    if (operation == 1):
        st[si] = (st[2 * si + 1] | st[2 * si + 2])
    else:
        st[si] = (st[2 * si + 1] ^ st[2 * si + 2])


def constructST(arr, n):
    x = int(math .ceil(math .log2(n)))
    max_size = 2 * int(pow(2, x)) - 1
    st = [0] * max_size
    operationAtRoot = (0 if x % 2 == 0 else 1)
    constructSTUtil(arr, 0, n - 1, st, 0, operationAtRoot)
    return st


if __name__ == "__main__":
    leaves = [1, 6, 3, 7, 5, 9, 10, 4]
    n = len(leaves)
    segmentTree = constructST(leaves, n)
    rootIndex = 0
    print("Value at Root Node = ", segmentTree[rootIndex])

# Expected output:
Value at Root Node =  3