giulio98/xlcost-single-prompt huggingface dataset:
# print first n numbers with exactly two set bits | prints first n numbers with two set bits ; initialize higher of two sets bits ; keep reducing n for every number with two set bits . ; consider all lower set bits for current higher set bit ; print current number ; if we have found n numbers ; consider next lower bit for current higher bit . ; increment higher set bit ; 
def printTwoSetBitNums(n):
    x = 1
    while (n > 0):
        y = 0
        while (y < x):
            print((1 << x) + (1 << y), end=" ")
            n -= 1
            if (n == 0):
                return
            y += 1
        x += 1


printTwoSetBitNums(4)

# Expected output:
3 5 6 9
# find even occurring elements in an array of limited range | function to find the even occurring elements in given array ; do for each element of array ; left - shift 1 by value of current element ; toggle the bit every time element gets repeated ; traverse array again and use _xor to find even occurring elements ; left - shift 1 by value of current element ; each 0 in _xor represents an even occurrence ; print the even occurring numbers ; set bit as 1 to avoid printing duplicates ; 
def printRepeatingEven(arr, n):
    axor = 0
    for i in range(0, n):
        pos = 1 << arr[i]
        axor ^= pos
    for i in range(0, n - 1):
        pos = 1 << arr[i]
        if (not (pos & axor)):
            print(arr[i], end=" ")
            axor ^= pos


arr = [9, 12, 23, 10, 12, 12, 15, 23, 14, 12, 15]
n = len(arr)
printRepeatingEven(arr, n)

# Expected output:
12 23 15
# cyclic redundancy check and modulo | returns xor of ' a ' and ' b ' ( both of same length ) ; initialize result ; traverse all bits , if bits are same , then xor is 0 , else 1 ; performs modulo - 2 division ; number of bits to be xored at a time . ; slicing the divident to appropriate length for particular step ; replace the divident by the result of xor and pull 1 bit down ; else : if leftmost bit is '0' if the leftmost bit of the dividend ( or the part used in each step ) is 0 , the step cannot use the regular divisor ; we need to use an all - 0 s divisor . ; increment pick to move further ; for the last n bits , we have to carry it out normally as increased value of pick will cause index out of bounds . ; function used at the sender side to encode data by appending remainder of modular division at the end of data . ; appends n - 1 zeroes at end of data ; append remainder in the original data ; 
def xor(a, b):
    result = []
    for i in range(1, len(b)):
        if a[i] == b[i]:
            result .append('0')
        else:
            result .append('1')
    return ''.join(result)


def mod2div(divident, divisor):
    pick = len(divisor)
    tmp = divident[0:pick]
    while pick < len(divident):
        if tmp[0] == '1':
            tmp = xor(divisor, tmp) + divident[pick]
            tmp = xor('0' * pick, tmp) + divident[pick]
        pick += 1
    if tmp[0] == '1':
        tmp = xor(divisor, tmp)
    else:
        tmp = xor('0' * pick, tmp)
    checkword = tmp
    return checkword


def encodeData(data, key):
    l_key = len(key)
    appended_data = data + '0' * (l_key - 1)
    remainder = mod2div(appended_data, key)
    codeword = data + remainder
    print("Remainder : ", remainder)
    print("Encoded Data (Data + Remainder) : ", codeword)


data = "100100"
key = "1101"
encodeData(data, key)

# Expected output:
Remainder :  000
Encoded Data (Data + Remainder) :  100100000
# check if a number is bleak | function to get no of set bits in binary representation of passed binary no . ; 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. ; 
def countSetBits(x):
    count = 0
    while (x):
        x = x & (x - 1)
        count = count + 1
    return count


def isBleak(n):
    for x in range(1, 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
# given a set , find xor of the xor 's of all subsets. | returns xor of all xor 's of given subset ; xor is 1 only when n is 1 , else 0 ; 
def findXOR(Set, n):
    if (n == 1):
        return Set[0]
    else:
        return 0


Set = [1, 2, 3]
n = len(Set)
print("XOR of XOR's of all subsets is ", findXOR(Set, n))

# Expected output:
XOR of XOR's of all subsets is  0
# find xor of two number without using xor operator | returns xor of x and y ; assuming 32 - bit integer ; find current bits in x and y ; if both are 1 then 0 else xor is same as or ; update result ; 
def myXOR(x, y):
    res = 0
    for i in range(31, -1, -1):
        b1 = x & (1 << i)
        b2 = y & (1 << i)
        b1 = min(b1, 1)
        b2 = min(b2, 1)
        xoredBit = 0
        if (b1 & b2):
            xoredBit = 0
        else:
            xoredBit = (b1 | b2)
        res <<= 1
        res |= xoredBit
    return res


x = 3
y = 5
print("XOR is", myXOR(x, y))

# Expected output:
XOR is 6
# find xor of two number without using xor operator | returns xor of x and y ; 
def myXOR(x, y):
    return ((x | y) & (~x | ~y))


x = 3
y = 5
print("XOR is", myXOR(x, y))

# Expected output:
XOR is 6
# how to swap two bits in a given integer ? | this function swaps bit at positions p1 and p2 in an integer n ; move p1 'th to rightmost side ; move p2 'th to rightmost side ; xor the two bits ; put the xor bit back to their original positions ; xor ' x ' with the original number so that the two sets are swapped ; 
def swapBits(n, p1, p2):
    bit1 = (n >> p1) & 1
    bit2 = (n >> p2) & 1
    x = (bit1 ^ bit2)
    x = (x << p1) | (x << p2)
    result = n ^ x
    return result


if __name__ == '__main__':
    res = swapBits(28, 0, 3)
    print("Result = ", res)

# Expected output:
Result =  21
# maximum length sub | function to return the maximum length of the required sub - array ; for the first consecutive pair of elements ; while a consecutive pair can be selected ; if current pair forms a valid sub - array ; 2 is the length of the current sub - array ; to extend the sub - array both ways ; while elements at indices l and r are part of a valid sub - array ; update the maximum length so far ; select the next consecutive pair ; return the maximum length ; 
def maxLength(arr, n):
    maxLen = 0
    i = 0
    j = i + 1
    while (j < n):
        if (arr[i] != arr[j]):
            maxLen = max(maxLen, 2)
            l = i - 1
            r = j + 1
            while (l >= 0 and r < n and arr[l] == arr[i] and arr[r] == arr[j]):
                l -= 1
                r += 1
            maxLen = max(maxLen, 2 * (r - j))
        i += 1
        j = i + 1
    return maxLen


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

# Expected output:
4
# freivaldâ €™ s algorithm to check if a matrix is product of two | python3 code to implement freivaldatms algorithm ; function to check if abx = cx ; generate a random vector ; now comput b * r for evaluating expression a * ( b * r ) - ( c * r ) ; now comput c * r for evaluating expression a * ( b * r ) - ( c * r ) ; now comput a * ( b * r ) for evaluating expression a * ( b * r ) - ( c * r ) ; finally check if value of expression a * ( b * r ) - ( c * r ) is 0 or not ; runs k iterations freivald . the value of k determines accuracy . higher value means higher accuracy . ; 

import random
N = 2


def freivald(a, b, c):
    r = [0] * N
    for i in range(0, N):
        r[i] = (int)(random .randrange(509090009) % 2)
    br = [0] * N
    for i in range(0, N):
        for j in range(0, N):
            br[i] = br[i] + b[i][j] * r[j]
    cr = [0] * N
    for i in range(0, N):
        for j in range(0, N):
            cr[i] = cr[i] + c[i][j] * r[j]
    axbr = [0] * N
    for i in range(0, N):
        for j in range(0, N):
            axbr[i] = axbr[i] + a[i][j] * br[j]
    for i in range(0, N):
        if (axbr[i] - cr[i] != 0):
            return False
    return True


def isProduct(a, b, c, k):
    for i in range(0, k):
        if (freivald(a, b, c) == False):
            return False
    return True


a = [[1, 1], [1, 1]]
b = [[1, 1], [1, 1]]
c = [[2, 2], [2, 2]]
k = 2
if (isProduct(a, b, c, k)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# expectation or expected value of an array | function to calculate expectation ; variable prb is for probability of each element which is same for each element ; calculating expectation overall ; returning expectation as sum ; 
def calc_Expectation(a, n):
    prb = 1 / n
    sum = 0
    for i in range(0, n):
        sum += (a[i] * prb)
    return float(sum)


n = 6
a = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
expect = calc_Expectation(a, n)
print("Expectation of array E(X) is : ", expect)

# Expected output:
Expectation of array E(X) is :  3.5
# sum of n | function to calculate the sum recursively ; base cases ; if n is odd ; if n is even ; function to print the value of sum ; 
def SumGPUtil(r, n, m):
    if n == 0:
        return 1
    if n == 1:
        return (1 + r) % m
    if n % 2 == 1:
        ans = (1 + r) * SumGPUtil(r * r % m, (n - 1) // 2, m)
    else:
        ans = 1 + r * (1 + r) * SumGPUtil(r * r % m, n // 2 - 1, m)
    return ans % m


def SumGP(a, r, N, M):
    answer = a * SumGPUtil(r, N, M)
    answer = answer % M
    print(answer)


if __name__ == '__main__':
    a = 1
    r = 4
    N = 10000
    M = 100000
    SumGP(a, r, N, M)

# Expected output:
12501
# length of longest subarray in which elements greater than k are more than elements not greater than k | function to find the length of a longest subarray in which elements greater than k are more than elements not greater than k ; create a new array in which we store 1 if a [ i ] > k otherwise we store - 1. ; taking prefix sum over it ; len will store maximum length of subarray ; this indicate there is at least one subarray of length mid that has sum > 0 ; check every subarray of length mid if it has sum > 0 or not if sum > 0 then it will satisfy our required condition ; x will store the sum of subarray of length mid ; satisfy our given condition ; check for higher length as we get length mid ; check for lower length as we did not get length mid ; 
def LongestSubarray(a, n, k):
    pre = [0 for i in range(n)]
    for i in range(n):
        if (a[i] > k):
            pre[i] = 1
        else:
            pre[i] = -1
    for i in range(1, n):
        pre[i] = pre[i - 1] + pre[i]
    Len = 0
    lo = 1
    hi = n
    while (lo <= hi):
        mid = (lo + hi) // 2
        ok = False
        for i in range(mid - 1, n):
            x = pre[i]
            if (i - mid >= 0):
                x -= pre[i - mid]
            if (x > 0):
                ok = True
                break
        if (ok):
            Len = mid
            lo = mid + 1
        else:
            hi = mid - 1
    return Len


a = [2, 3, 4, 5, 3, 7]
k = 3
n = len(a)
print(LongestSubarray(a, n, k))

# Expected output:
5
# choose points from two ranges such that no point lies in both the ranges | function to find the required points ; 
def findPoints(l1, r1, l2, r2):
    x = min(l1, l2)if (l1 != l2)else -1
    y = max(r1, r2)if (r1 != r2)else -1
    print(x, y)


if __name__ == "__main__":
    l1 = 5
    r1 = 10
    l2 = 1
    r2 = 7
    findPoints(l1, r1, l2, r2)

# Expected output:
1 10
# tail recursion | a non - tail - recursive function . the function is not tail recursive because the value returned by fact ( n - 1 ) is used in fact ( n ) and call to fact ( n - 1 ) is not the last thing done by fact ( n ) ; 
def fact(n):
    if (n == 0):
        return 1
    return n * fact(n - 1)


print(fact(5))

# Expected output:
120
# minimum number of working days required to achieve each of the given scores | function to find the minimum number of days required to work to at least arr [ i ] points for every array element ; traverse the array p [ ] ; find the prefix sum ; traverse the array arr [ ] ; find the minimum index of the array having value at least arr [ i ] ; if the index is not - 1 ; otherwise ; function to find the lower bound of n using binary search ; stores the lower bound ; stores the upper bound ; stores the minimum index having value is at least n ; iterater while i <= j ; stores the mid index of the range [ i , j ] ; if p [ mid ] is at least n ; update the value of mid to index ; update the value of j ; update the value of i ; return the resultant index ; 
def binarySeach(P, N):
    i = 0
    j = len(P) - 1
    index = -1
    while (i <= j):
        mid = i + (j - i) // 2
        if (P[mid] >= N):
            index = mid
            j = mid - 1
        else:
            i = mid + 1
    return index


def minDays(P, arr):
    for i in range(1, len(P)):
        P[i] += P[i] + P[i - 1]
    for i in range(len(arr)):
        index = binarySeach(P, arr[i])
        if (index != -1):
            print(index + 1, end=" ")
        else:
            print(-1, end=" ")


if __name__ == '__main__':
    arr = [400, 200, 700, 900, 1400]
    P = [100, 300, 400, 500, 600]
    minDays(P, arr)

# Expected output:
2 2 2 3 3
# maximize profit that can be earned by selling an item among n buyers | python3 program for the above approach ; function to find the maximum profit earned by selling an item among n buyers ; stores the maximum profit ; stores the price of the item ; sort the array ; traverse the array ; count of buyers with budget >= arr [ i ] ; update the maximum profit ; return the maximum possible price ; 

import sys


def maximumProfit(arr, N):
    ans = -sys .maxsize - 1
    price = 0
    arr .sort()
    for i in range(N):
        count = (N - i)
        if (ans < count * arr[i]):
            price = arr[i]
            ans = count * arr[i]
    return price


if __name__ == "__main__":
    arr = [22, 87, 9, 50, 56, 43]
    print(maximumProfit(arr, 6))

# Expected output:
43
# maximum length palindromic substring for every index such that it starts and ends at that index | function to return true if s [ i ... j ] is a palindrome ; iterate until i < j ; if unequal character encountered ; otherwise ; function to find for every index , longest palindromic substrings starting or ending at that index ; stores the maximum palindromic substring length for each index ; traverse the string ; stores the maximum length of palindromic substring ; consider that palindromic substring ends at index i ; if current character is a valid starting index ; if s [ i , j ] is palindrome , ; update the length of the longest palindrome ; consider that palindromic substring starts at index i ; if current character is a valid ending index ; if str [ i , j ] is palindrome ; update the length of the longest palindrome ; update length of the longest palindromic substring for index i ; print the length of the longest palindromic substring ; 
def isPalindrome(S, i, j):
    while (i < j):
        if (S[i] != S[j]):
            return False
        i += 1
        j -= 1
    return True


def printLongestPalindrome(S, N):
    palLength = [0 for i in range(N)]
    for i in range(N):
        maxlength = 1
        for j in range(i):
            if (S[j] == S[i]):
                if (isPalindrome(S, j, i)):
                    maxlength = i - j + 1
                    break
        j = N-1
        while (j > i):
            if (S[j] == S[i]):
                if (isPalindrome(S, i, j)):
                    maxlength = max(j - i + 1, maxlength)
                    break
            j -= 1
        palLength[i] = maxlength
    for i in range(N):
        print(palLength[i], end=" ")


if __name__ == '__main__':
    S = "bababa"
    N = len(S)
    printLongestPalindrome(S, N)

# Expected output:
5 5 3 3 5 5
# sum of array elements which are multiples of a given number | function to find the sum of array elements which are multiples of n ; stores the sum ; traverse the array ; print total sum ; 
def mulsum(arr, n, N):
    sums = 0
    for i in range(0, n):
        if arr[i] % N == 0:
            sums = sums + arr[i]
    print(sums)


if __name__ == "__main__":
    arr = [1, 2, 3, 5, 6]
    n = len(arr)
    N = 3
    mulsum(arr, n, N)

# Expected output:
9
# farthest index that can be reached from the kth index of given array by given operations | function to find the farthest index that can be reached ; declare a priority queue ; iterate the array ; if current element is greater than the next element ; otherwise , store their difference ; push diff into pq ; if size of pq exceeds y ; decrease x by the top element of pq ; remove top of pq ; if x is exhausted ; current index is the farthest possible ; print n - 1 as farthest index ; 
def farthestHill(arr, X, Y, N, K):
    pq = []
    for i in range(K, N - 1, 1):
        if (arr[i] >= arr[i + 1]):
            continue
        diff = arr[i + 1] - arr[i]
        pq .append(diff)
        if (len(pq) > Y):
            X -= pq[-1]
            pq[-1]
        if (X < 0):
            print(i)
            return
    print(N - 1)


arr = [4, 2, 7, 6, 9, 14, 12]
X = 5
Y = 1
K = 0
N = len(arr)
farthestHill(arr, X, Y, N, K)

# Expected output:
4
# lexicographically largest string possible consisting of at most k consecutive similar characters | function to return nearest lower character ; traverse charset from start - 1 ; if no character can be appended ; function to find largest string ; stores the frequency of characters ; traverse the string ; append larger character ; decrease count in charset ; increase count ; check if count reached to charlimit ; find nearest lower char ; if no character can be appended ; append nearest lower character ; reset count for next calculation ; return new largest string ; 
def nextAvailableChar(charset, start):
    for i in range(start - 1, -1, -1):
        if (charset[i] > 0):
            charset[i] -= 1
            return chr(i + ord('a'))
    return '\0'


def newString(originalLabel, limit):
    n = len(originalLabel)
    charset = [0] * (26)
    newStrings = ""
    for i in originalLabel:
        charset[ord(i) - ord('a')] += 1
    for i in range(25, -1, -1):
        count = 0
        while (charset[i] > 0):
            newStrings += chr(i + ord('a'))
            charset[i] -= 1
            count += 1
            if (charset[i] > 0 and count == limit):
                next = nextAvailableChar(charset, i)
                if (next == '\0'):
                    return newStrings
                newStrings += next
                count = 0
    return newStrings


if __name__ == "__main__":
    S = "ccbbb"
    K = 2
    print(newString(S, K))

# Expected output:
ccbb
# rearrange array by interchanging positions of even and odd elements in the given array | function to replace odd elements with even elements and vice versa ; length of the array ; traverse the given array ; if arr [ i ] is visited ; find the next odd element ; find next even element ; mark them visited ; swap them ; print the final array ; 
def swapEvenOdd(arr):
    n = len(arr)
    o = -1
    e = -1
    for i in range(n):
        if (arr[i] < 0):
            continue
        r = -1
        if (arr[i] % 2 == 0):
            o += 1
            while (arr[o] % 2 == 0 or arr[o] < 0):
                o += 1
            r = o
        else:
            e += 1
            while (arr[e] % 2 == 1 or arr[e] < 0):
                e += 1
            r = e
        arr[i] *= -1
        arr[r] *= -1
        tmp = arr[i]
        arr[i] = arr[r]
        arr[r] = tmp
    for i in range(n):
        print((-1 * arr[i]), end=" ")


if __name__ == '__main__':
    arr = [1, 3, 2, 4]
    swapEvenOdd(arr)

# Expected output:
2 4 1 3
# check if a palindromic string can be obtained by concatenating substrings split from same indices of two 
def check(a, b, n):
    i, j = 0, n - 1
    while (i < n):
        if (a[i] != b[j]):
            break
        i += 1
        j -= 1
        xa = a[i:j + 1]
        xb = b[i:j + 1]
        if (xa == xa[::-1] or xb == xb[::-1]):
            return True


a = "xbdef"
b = "cabex"
if check(a, b, len(a)) or check(b, a, len(a)):
    print(True)
else:
    print(False)

# Expected output:
False
# maximize length of subarray having equal elements by adding at most k | function to find the maximum number of indices having equal elements after adding at most k numbers ; sort the array in ascending order ; make prefix sum array ; initialize variables ; update mid ; check if any subarray can be obtained of length mid having equal elements ; decrease max to mid ; function to check if a subarray of length len consisting of equal elements can be obtained or not ; sliding window ; last element of the sliding window will be having the max size in the current window ; the current number of element in all indices of the current sliding window ; if the current number of the window , added to k exceeds totalnumbers ; 
def check(pSum, lenn, k, a):
    i = 0
    j = lenn
    while (j <= len(a)):
        maxSize = a[j - 1]
        totalNumbers = maxSize * lenn
        currNumbers = pSum[j] - pSum[i]
        if (currNumbers + k >= totalNumbers):
            return True
        else:
            i += 1
            j += 1
    return False

def maxEqualIdx(arr, k):
    arr .sort()
    prefixSum = [0] * (len(arr) + 1)
    prefixSum[1] = arr[0]
    for i in range(1, len(prefixSum) - 1, 1):
        prefixSum[i + 1] = prefixSum[i] + arr[i]
    max = len(arr)
    min = 1
    ans = 1
    while (min <= max):
        mid = (max + min) // 2
        if (check(prefixSum, mid, k, arr)):
            ans = mid
            min = mid + 1
        else:
            max = mid - 1
    return ans


arr = [1, 1, 1]
k = 7
print(maxEqualIdx(arr, k))

# Expected output:
3
# sum of product of all pairs of a binary array | function to print the sum of product of all pairs of the given array ; stores count of one in the given array ; stores the size of the given array ; if current element is 1 ; increase count ; return the sum of product of all pairs ; 
def productSum(arr):
    cntOne = 0
    N = len(arr)
    for i in range(N):
        if (arr[i] == 1):
            cntOne += 1
    return cntOne * (cntOne - 1) // 2


arr = [0, 1, 1, 0, 1]
print(productSum(arr))

# Expected output:
3
# minimum value of x that can be added to n to minimize sum of the digits to ã ¢ â €°¤ k | ''python program for the above approach ; ''function to find the minimum number needed to be added so that the sum of the digits does not exceed k ;  ;  ; '' add the digits of num2 ; ''if the sum of the digits of n  is less than or equal to k ; '' no number needs to  be added ; '' otherwise ; '' calculate the sum of digits  from least significant digit ; '' if sum exceeds k ; '' increase previous  digit by 1 ; '' add zeros to the end ; '' calculate difference  between the result and n ; '' return the result ; ''

import math


def minDigits(N, K):
    digits_num = int(math.floor(math.log(N) + 1))

    temp_sum = 0
    temp = digits_num
    result = 0
    X = 0
    var = 0
    sum1 = 0
    num2 = N
    while (num2 != 0):
        sum1 += num2 % 10
        num2 /= 10
    if (sum1 <= K):
        X = 0
    else:
        while (temp > 0):
            var = int(N // (pow(10, temp - 1)))
            temp_sum += var % 10
            if (temp_sum >= K):
                var = var // 10
                var += 1
                result = var * int(pow(10, temp))
                break

            temp -= 1
        X = result - N
        return X

    return -1


if __name__ == '__main__':
    N = 11
    K = 1
    print(minDigits(N, K))

# Expected output:
89