giulio98/xlcost-single-prompt huggingface dataset:
# count pairs with bitwise xor as odd number | function to count number of odd pairs ; find all pairs ; return number of odd pair ; 
def findOddPair(A, N):
    count = 0
    for i in range(0, N):
        if (A[i] % 2 == 0):
            count += 1
    return count * (N - count)


if __name__ == '__main__':
    a = [5, 4, 7, 2, 1]
    n = len(a)
    print(findOddPair(a, n))

# Expected output:
6
# bitwise or ( or | ) of a range | returns the most significant bit position ( msb ) ; returns the bitwise or of all integers between l and r ; find the msb position in l ; find the msb position in r ; add this value until msb_p1 and msb_p2 are same ; ; calculate msb_p1 and msb_p2 ; find the max of msb_p1 and msb_p2 ; set all the bits from msb_p1 upto 0 th bit in the result ; 
def MSBPosition(N):
    msb_p = -1
    while (N):
        N = N >> 1
        msb_p += 1
    return msb_p


def findBitwiseOR(L, R):
    res = 0
    msb_p1 = MSBPosition(L)
    msb_p2 = MSBPosition(R)
    while (msb_p1 == msb_p2):
        res_val = (1 << msb_p1)
        res += res_val
        L -= res_val
        R -= res_val
        msb_p1 = MSBPosition(L)
        msb_p2 = MSBPosition(R)
    msb_p1 = max(msb_p1, msb_p2)
    for i in range(msb_p1, -1, -1):
        res_val = (1 << i)
        res += res_val
    return res


if __name__ == "__main__":
    L, R = 12, 18
    print(findBitwiseOR(L, R))

# Expected output:
31
# maximize the bitwise or of an array | function to maximize the bitwise or sum ; compute x ^ k ; find prefix bitwise or ; find suffix bitwise or ; find maximum or value ; 
def maxOR(arr, n, k, x):
    preSum = [0] * (n + 1)
    suffSum = [0] * (n + 1)
    pow = 1
    for i in range(0, k):
        pow *= x
    preSum[0] = 0
    for i in range(0, n):
        preSum[i + 1] = preSum[i] | arr[i]
    suffSum[n] = 0
    for i in range(n - 1, -1, -1):
        suffSum[i] = suffSum[i + 1] | arr[i]
    res = 0
    for i in range(0, n):
        res = max(res, preSum[i] | (arr[i] * pow) | suffSum[i + 1])
    return res


arr = [1, 2, 4, 8]
n = len(arr)
k = 2
x = 3
print(maxOR(arr, n, k, x))

# Expected output:
79
# how to turn on a particular bit in a number ? | returns a number that has all bits same as n except the k 'th bit which is made 1 ; k must be greater than 0 ; do | of n with a number with all unset bits except the k 'th bit ; 
def turnOnK(n, k):
    if (k <= 0):
        return n
    return (n | (1 << (k - 1)))


n = 4
k = 2
print(turnOnK(n, k))

# Expected output:
6
# minimum sum of two numbers formed from digits of an array | returns sum of two numbers formed from all digits in a [ ] ; sorted the elements ; 
def minSum(a, n):
    a = sorted(a)
    num1, num2 = 0, 0
    for i in range(n):
        if i % 2 == 0:
            num1 = num1 * 10 + a[i]
        else:
            num2 = num2 * 10 + a[i]
    return num2 + num1


arr = [5, 3, 0, 7, 4]
n = len(arr)
print("The required sum is", minSum(arr, n))

# Expected output:
The required sum is 82
# find value of k | python 3 program to find k - th bit from right ; 
def printKthBit(n, k):
    print((n & (1 << (k - 1))) >> (k - 1))


n = 13
k = 2
printKthBit(n, k)

# Expected output:
0
# odd numbers in n | function to get no of set bits in binary representation of positive integer n ; count number of 1 's in binary  representation of n. ; number of odd numbers in n - th row is 2 raised to power the count . ; 
def countSetBits(n):
    count = 0
    while n:
        count += n & 1
        n >>= 1
    return count


def countOfOddPascal(n):
    c = countSetBits(n)
    return pow(2, c)


n = 20
print(countOfOddPascal(n))

# Expected output:
4
# queries on xor of xors of all subarrays | python 3 program to answer queries on xor of xors of all subarray ; output for each query ; if number of element is even . ; if number of element is odd . ; if l is even ; if l is odd ; wrapper function ; evaluating prefixodd and prefixeven ; 

N = 100


def ansQueries(prefeven, prefodd, l, r):
    if ((r - l + 1) % 2 == 0):
        print("0")
    else:
        if (l % 2 == 0):
            print(prefeven[r] ^ prefeven[l - 1])
        else:
            print(prefodd[r] ^ prefodd[l - 1])


def wrapper(arr, n, l, r, q):
    prefodd = [0] * N
    prefeven = [0] * N
    for i in range(1, n + 1):
        if ((i) % 2 == 0):
            prefeven[i] = arr[i - 1] ^ prefeven[i - 1]
            prefodd[i] = prefodd[i - 1]
        else:
            prefeven[i] = prefeven[i - 1]
            prefodd[i] = prefodd[i - 1] ^ arr[i - 1]
    i = 0
    while (i != q):
        ansQueries(prefeven, prefodd, l[i], r[i])
        i += 1


if __name__ == "__main__":
    arr = [1, 2, 3, 4, 5]
    n = len(arr)
    l = [1, 1, 2]
    r = [2, 3, 4]
    q = len(l)
    wrapper(arr, n, l, r, q)

# Expected output:
0
2
6
# Variation in Nim Game | Function to return final grundy Number ( G ) of game ; if pile size is odd ; We XOR pile size + 1 ; if pile size is even ; We XOR pile size - 1 ; Game with 3 piles ; pile with different sizes ; Function to return result of game ; if ( res == 0 ) : if G is zero ; else : if G is non zero
def solve(p, n):
    G = 0
    for i in range(n):
        if (p[i] % 2 != 0):
            G ^= (p[i] + 1)
        else:
            G ^= (p[i] - 1)
    return G


n = 3
p = [32, 49, 58]
res = solve(p, n)
print("Player 2 wins")
print("Player 1 wins")

# Expected output:
Player 2 wins
Player 1 wins
# maximum and value of a pair in an array | utility function to check number of elements having set msb as of pattern ; function for finding maximum and value pair ; iterate over total of 30 bits from msb to lsb ; find the count of element having set msb ; if count >= 2 set particular bit in result ; 
def checkBit(pattern, arr, n):
    count = 0
    for i in range(0, n):
        if ((pattern & arr[i]) == pattern):
            count = count + 1
    return count


def maxAND(arr, n):
    res = 0
    for bit in range(31, -1, -1):
        count = checkBit(res | (1 << bit), arr, n)
        if (count >= 2):
            res = res | (1 << bit)
    return res


arr = [4, 8, 6, 2]
n = len(arr)
print("Maximum AND Value = ", maxAND(arr, n))

# Expected output:
Maximum AND Value =  4
# minimum flips to make all 1 s in left and 0 s in right | set 1 ( using bitmask ) | function to count minimum number of flips ; this is converting string s into integer of base 2 ( if s = '100' then num = 4 ) ; initialize minxor with n that can be maximum number of flips ; right shift 1 by ( n - 1 ) bits ; calculate bitwise xor of num and mask ; math . min ( a , b ) returns minimum of a and b return minimum number of flips till that digit ; function to count number of 1 s ; 
def countones(n):
    c = 0
    while (n > 0):
        n = n & (n - 1)
        c += 1
    return c

def findMiniFlip(nums):
    n = len(nums)
    s = ''
    for i in range(n):
        s += str(nums[i])
    num = int(s, 2)
    minXor = n
    mask = (1 << (n - 1))
    while (n - 1 > 0):
        temp = (num ^ mask)
        minXor = min(minXor, countones(temp))
        n -= 1
        mask = (mask | (1 << n - 1))
    return minXor


if __name__ == "__main__":
    nums = [1, 0, 1, 1, 0, 0, 0]
    n = findMiniFlip(nums)
    print(n)

# Expected output:
1
# check if a number is power of 8 or not | python3 program to check if a number is power of 8 ; function to check if power of 8 ; calculate log8 ( n ) ; check if i is an integer or not ; 

from math import log, trunc


def checkPowerof8(n):
    i = log(n, 8)
    return (i - trunc(i) < 0.000001)


n = 65
if checkPowerof8(n):
    print("Yes")
else:
    print("No")

# Expected output:
No
# find the n | utility function which is used to convert binary string into integer ; convert binary string into integer ; function to find nth binary palindrome number ; stores the binary palindrome string ; base case ; add 2 nd binary palindrome string ; runs till the nth binary palindrome number ; remove curr binary palindrome string from queue ; if n == 0 then we find the n 'th binary  palindrome so we return our answer ; calculate length of curr binary palindrome string ; if length is even . so it is our first case we have two choices ; if length is odd . so it is our second case we have only one choice ; 
def convertStringToInt(s):
    ans = 0
    for i in range(len(s)):
        ans = ans * 2 + (ord(s[i]) - ord('0'))
    return ans


def getNthNumber(n):
    q = []
    if (n == 1):
        return 1
    n = n - 1
    q .append("11")
    while (len(q) != 0):
        curr = q .pop(0)
        n -= 1
        if (n == 0):
            return convertStringToInt(curr)
        lenn = len(curr)
        if (len(curr) % 2 == 0):
            q .append(curr[0:int(lenn / 2)] + "0" + curr[int(lenn / 2):])
            q .append(curr[0:int(lenn / 2)] + "1" + curr[int(lenn / 2):])
        else:
            midChar = curr[int(lenn / 2)]
            q .append(curr[0:int(lenn / 2)] + midChar + curr[int(lenn / 2):])
    return 0


n = 9
print(getNthNumber(n))

# Expected output:
27
# check if binary representation of a given number and its complement are anagram | an efficient python3 program to check if binary representations of a number and it 's complement are anagram. ; returns true if binary representations of a and b are anagram . ; _popcnt64 ( a ) gives number of 1 's present  in binary representation of a. if number  of 1s is half of total bits, return true. ; 

ULL_SIZE = 64


def bit_anagram_check(a):
    return (bin(a).count("1") == (ULL_SIZE >> 1))


a = 4294967295
print(int(bit_anagram_check(a)))

# Expected output:
1
# sum of numbers with exactly 2 bits set | to calculate sum of numbers ; find numbers whose 2 bits are set ; if number is greater then n we don 't include this in sum ; return sum of numbers ; 
def findSum(n):
    sum = 0
    i = 1
    while ((1 << i) < n):
        for j in range(0, i):
            num = (1 << i) + (1 << j)
            if (num <= n):
                sum += num
        i += 1
    return sum


n = 10
print(findSum(n))

# Expected output:
33
# position of rightmost different bit | python3 implementation to find the position of rightmost different bit in two number . ; function to find rightmost different bit in two numbers . ; 

from math import floor, log10


def posOfRightMostDiffBit(m, n):
    return floor(log10(pow(m ^ n, 2))) + 2


if __name__ == '__main__':
    m, n = 52, 4
    print("Position = ", posOfRightMostDiffBit(m, n))

# Expected output:
Position =  5
# set the k | function to set the kth bit ; kth bit of n is being set by this operation ; 
def setKthBit(n, k):
    return ((1 << k) | n)


n = 10
k = 2
print("Kth bit set number = ", setKthBit(n, k))

# Expected output:
Kth bit set number =  14
# reverse an array without using subtract sign â €˜ | function to reverse array ; trick to assign - 1 to a variable ; reverse array in simple manner ; swap ith index value with ( n - i - 1 ) th index value ; 
def reverseArray(arr, n):
    import sys
    x = -sys .maxsize // sys .maxsize
    for i in range(n // 2):
        arr[i], arr[n + (x * i) + x] = arr[n + (x * i) + x], arr[i]


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

# Expected output:
6 1 2 7 3 5
# reverse an array without using subtract sign â €˜ | function to reverse array ; reverse array in simple manner ; swap ith index value with ( n - i - 1 ) th index value note : a - b = a + ~ b + 1 so n - i = n + ~ i + 1 then n - i - 1 = ( n + ~ i + 1 ) + ~ 1 + 1 ; 
def reverseArray(arr, n):
    for i in range(n // 2):
        arr[i], arr[(n + ~i + 1) + ~1 + 1] = arr[(n + ~i + 1) + ~1 + 1], arr[i]


arr = [5, 3, 7, 2, 1, 6]
n = len(arr)
reverseArray(arr, n)
for i in range(n):
    print(arr[i], end=" ")

# Expected output:
6 1 2 7 3 5
# maximum xor value of a pair from a range | method to get maximum xor value in range [ l , r ] ; get xor of limits ; loop to get msb position of l ^ r ; construct result by adding 1 , msbpos times ; 
def maxXORInRange(L, R):
    LXR = L ^ R
    msbPos = 0
    while (LXR):
        msbPos += 1
        LXR >>= 1
    maxXOR, two = 0, 1
    while (msbPos):
        maxXOR += two
        two <<= 1
        msbPos -= 1
    return maxXOR


L, R = 8, 20
print(maxXORInRange(L, R))

# Expected output:
31
# numbers whose bitwise or and sum with n are equal | function to find total 0 bit in a number ; function to find count of non - negative numbers less than or equal to n , whose bitwise or and sum with n are equal . ; count number of zero bit in n ; power of 2 to count ; 
def CountZeroBit(n):
    count = 0
    while (n):
        if (not (n & 1)):
            count += 1
        n >>= 1
    return count


def CountORandSumEqual(N):
    count = CountZeroBit(N)
    return (1 << count)


N = 10
print(CountORandSumEqual(N))

# Expected output:
4
# count smaller numbers whose xor with n produces greater value | python program to count numbers whose xor with n produces a value more than n . ; position of current bit in n ; traverse bits from lsb to msb ; initialize result ; if current bit is 0 , then there are 2 ^ k numbers with current bit 1 and whose xor with n produces greater value ; increase position for next bit ; reduce n to find next bit ; 
def countNumbers(n):
    k = 0
    count = 0
    while (n > 0):
        if ((n & 1) == 0):
            count += pow(2, k)
        k += 1
        n >>= 1
    return count


n = 11
print(countNumbers(n))

# Expected output:
4
# count all pairs with given xor | returns count of pairs in arr [ 0. . n - 1 ] with xor value equals to x . ; create empty set that stores the visiting element of array . ; if there exist an element in set s with xor equals to x ^ arr [ i ] , that means there exist an element such that the xor of element with arr [ i ] is equal to x , then increment count . ; make element visited ; return total count of pairs with xor equal to x ; 
def xorPairCount(arr, n, x):
    result = 0
    s = set()
    for i in range(0, n):
        if (x ^ arr[i] in s):
            result = result + 1
        s .add(arr[i])
    return result


if __name__ == "__main__":
    arr = [5, 4, 10, 15, 7, 6]
    n = len(arr)
    x = 5
    print("Count of pair with given XOR = " + str(xorPairCount(arr, n, x)))

# Expected output:
Count of pair with given XOR = 1
# Multiples of 4 ( An Interesting Method ) | Returns true if n is a multiple of 4. ; Find XOR of all numbers from 1 to n ; If XOR is equal n , then return true ; Printing multiples of 4 using above method
def isMultipleOf4(n):
    if (n == 1):
        return False
    XOR = 0
    for i in range(1, n + 1):
        XOR = XOR ^ i
    return (XOR == n)


for n in range(0, 43):
    if (isMultipleOf4(n)):
        print(n, end=" ")

# Expected output:
0 4 8 12 16 20 24 28 32 36 40
# check if a number is bleak | an efficient python 3 program to check bleak number ; function to get no of set bits in binary representation of passed binary no . ; a function to return ceiling of log x in base 2. for example , it returns 3 for 8 and 4 for 9. ; returns true if n is bleak ; check for all numbers ' x ' smaller than n . if x + countsetbits ( x ) becomes n , then n can 't be bleak ; 

import math


def countSetBits(x):
    count = 0
    while (x):
        x = x & (x - 1)
        count = count + 1
    return count


def ceilLog2(x):
    count = 0
    x = x - 1
    while (x > 0):
        x = x >> 1
        count = count + 1
    return count


def isBleak(n):
    for x in range((n - ceilLog2(n)), n):
        if (x + countSetBits(x) == n):
            return False
    return True


if (isBleak(3)):
    print("Yes")
else:
    print("No")
if (isBleak(4)):
    print("Yes")
else:
    print("No")

# Expected output:
No
Yes
# count strings with consecutive 1 's | returns count of n length binary strings with consecutive 1 's ; count binary strings without consecutive 1 's.  see the approach discussed on be  ( http:goo.gl/p8a3sw ) ; subtract a [ n - 1 ] + b [ n - 1 ] from 2 ^ n ; 
def countStrings(n):
    a = [0] * n
    b = [0] * n
    a[0] = b[0] = 1
    for i in range(1, n):
        a[i] = a[i - 1] + b[i - 1]
        b[i] = a[i - 1]
    return (1 << n) - a[n - 1] - b[n - 1]


print(countStrings(5))

# Expected output:
19
# how to swap two bits in a given integer ? | python code for swapping given bits of a number ; left - shift 1 p1 and p2 times and using xor ; 
def swapBits(n, p1, p2):
    n ^= 1 << p1
    n ^= 1 << p2
    return n


print("Result =", swapBits(28, 0, 3))

# Expected output:
Result = 21
# maximum length sub | function to return the maximum length of the required sub - array ; to store the maximum length for a valid subarray ; to store the count of contiguous similar elements for previous group and the current group ; if current element is equal to the previous element then it is a part of the same group ; else update the previous group and start counting elements for the new group ; update the maximum possible length for a group ; return the maximum length of the valid subarray ; 
def maxLength(a, n):
    maxLen = 0
    prev_cnt = 0
    curr_cnt = 1
    for i in range(1, n):
        if (a[i] == a[i - 1]):
            curr_cnt += 1
        else:
            prev_cnt = curr_cnt
            curr_cnt = 1
        maxLen = max(maxLen, min(prev_cnt, curr_cnt))
    return (2 * maxLen)


arr = [1, 1, 1, 0, 0, 1, 1]
n = len(arr)
print(maxLength(arr, n))

# Expected output:
4
# check if two nodes are cousins in a binary tree | a binary tree node ; recursive function to check if two nodes are siblings ; base case ; recursive function to find level of node ' ptr ' in a binary tree ; base case ; return level if node is present in left subtree ; else search in right subtree ; returns 1 if a and b are cousins , otherwise 0 ; 1. the two nodes should be on the same level in the binary tree the two nodes should not be siblings ( means that they should not have the smae parent node ; 

class Node:
    def __init__(self, data):
        self .data = data
        self .left = None
        self .right = None


def isSibling(root, a, b):
    if root is None:
        return 0
    return (
        (
            root .left == a and root .right == b) or (
            root .left == b and root .right == a) or isSibling(
                root .left,
                a,
                b) or isSibling(
                    root .right,
                    a,
            b))


def level(root, ptr, lev):
    if root is None:
        return 0
    if root == ptr:
        return lev
    l = level(root .left, ptr, lev + 1)
    if l != 0:
        return l
    return level(root .right, ptr, lev + 1)


def isCousin(root, a, b):
    if ((level(root, a, 1) == level(root, b, 1))
            and not (isSibling(root, a, b))):
        return 1
    else:
        return 0



root = Node(1)
root .left = Node(2)
root .right = Node(3)
root .left .left = Node(4)
root .left .right = Node(5)
root .left .right .right = Node(15)
root .right .left = Node(6)
root .right .right = Node(7)
root .right .left .right = Node(8)
node1 = root .left .right
node2 = root .right .right
print("Yes")if isCousin(root, node1, node2) == 1 else print("No")

# Expected output:
Yes
# check if all leaves are at same level | a binary tree node ; recursive function which check whether all leaves are at same level ; base case ; if a tree node is encountered ; when a leaf node is found first time ; set first leaf found ; if this is not first leaf node , compare its level with first leaf 's level ; if this is not first leaf node , compare its level with first leaf 's level ; the 

class Node:
    def __init__(self, data):
        self .data = data
        self .left = None
        self .right = None


def checkUtil(root, level):
    if root is None:
        return True
    if root .left is None and root .right is None:
        if check .leafLevel == 0:
            check .leafLevel = level
            return True
        return level == check .leafLevel
    return (
        checkUtil(
            root .left,
            level +
            1) and checkUtil(
            root .right,
            level +
            1))


def check(root):
    level = 0
    check .leafLevel = 0
    return (checkUtil(root, level))



root = Node(12)
root .left = Node(5)
root .left .left = Node(3)
root .left .right = Node(9)
root .left .left .left = Node(1)
root .left .right .left = Node(2)
if (check(root)):
    print("Leaves are at same level")
else:
    print("Leaves are not at same level")

# Expected output:
Leaves are at same level
# sorting a queue without extra space | python3 program to implement sorting a queue data structure ; queue elements after sortedindex are already sorted . this function returns index of minimum element from front to sortedindex ; this is dequeue ( ) in c ++ stl ; we add the condition i <= sortedindex because we don 't want to traverse   on the sorted part of the queue,   which is the right part.  ; this is enqueue ( ) in c ++ stl ; moves given minimum element to rear of queue ; sortqueue function ; 

from queue import Queue


def minIndex(q, sortedIndex):
    min_index = -1
    min_val = 999999999999
    n = q .qsize()
    for i in range(n):
        curr = q .queue[0]
        q .get()
        if (curr <= min_val and i <= sortedIndex):
            min_index = i
            min_val = curr
        q .put(curr)
    return min_index


def insertMinToRear(q, min_index):
    min_val = None
    n = q .qsize()
    for i in range(n):
        curr = q .queue[0]
        q .get()
        if (i != min_index):
            q .put(curr)
        else:
            min_val = curr
    q .put(min_val)


def sortQueue(q):
    for i in range(1, q .qsize() + 1):
        min_index = minIndex(q, q .qsize() - i)
        insertMinToRear(q, min_index)


if __name__ == '__main__':
    q = Queue()
    q .put(30)
    q .put(11)
    q .put(15)
    q .put(4)
    sortQueue(q)
    while (q .empty() == False):
        print(q .queue[0], end=" ")
        q .get()

# Expected output:
4 11 15 30
# sliding window maximum ( maximum of all subarrays of size k ) | python program to find the maximum for each and every contiguous subarray of size k ; a deque ( double ended queue ) based method for printing maximum element of all subarrays of size k ; create a double ended queue , qi that will store indexes of array elements . the queue will store indexes of useful elements in every window and it will maintain decreasing order of values from front to rear in qi , i . e . , arr [ qi . front [ ] ] to arr [ qi . rear ( ) ] are sorted in decreasing order ; process first k ( or first window ) elements of array ; for every element , the previous smaller elements are useless so remove them from qi ; remove from rear ; add new element at rear of queue ; process rest of the elements , i . e . from arr [ k ] to arr [ n - 1 ] ; the element at the front of the queue is the largest element of previous window , so print it ; remove the elements which are out of this window ; remove from front of deque ; remove all elements smaller than the currently being added element ( remove useless elements ) ; add current element at the rear of qi ; print the maximum element of last window ; 

from collections import deque


def printMax(arr, n, k):
    Qi = deque()
    for i in range(k):
        while Qi and arr[i] >= arr[Qi[-1]]:
            Qi .pop()
        Qi .append(i)
    for i in range(k, n):
        print(str(arr[Qi[0]]) + " ", end="")
        while Qi and Qi[0] <= i - k:
            Qi .popleft()
        while Qi and arr[i] >= arr[Qi[-1]]:
            Qi .pop()
        Qi .append(i)
    print(str(arr[Qi[0]]))


if __name__ == "__main__":
    arr = [12, 1, 78, 90, 57, 89, 56]
    k = 3
    printMax(arr, len(arr), k)

# Expected output:
78 90 90 90 89