giulio98/xlcost-single-prompt huggingface dataset:
# count set bits in an integer | python3 program to count set bits by pre - storing count set bits in nibbles . ; recursively get nibble of a given number and map them in the array ; find last nibble ; use pre - stored values to find count in last nibble plus recursively add remaining nibbles . ; 

num_to_bits = [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4]


def countSetBitsRec(num):
    nibble = 0
    if (0 == num):
        return num_to_bits[0]
    nibble = num & 0xf
    return num_to_bits[nibble] + countSetBitsRec(num >> 4)


num = 31
print(countSetBitsRec(num))

# Expected output:
5
# program to find parity | function to get parity of number n . it returns 1 if n has odd parity , and returns 0 if n has even parity ; 
def getParity(n):
    parity = 0
    while n:
        parity = ~parity
        n = n & (n - 1)
    return parity


n = 7
print("Parity of no ", n, " = ", ("odd"if getParity(n)else "even"))

# Expected output:
Parity of no  7  =  odd
# program to find whether a no is power of two | python3 program to find whether a no is power of two ; function to check log base 2 ; function to check if x is power of 2 ; 

import math


def Log2(x):
    if x == 0:
        return false
    return (math .log10(x) / math .log10(2))


def isPowerOfTwo(n):
    return (math .ceil(Log2(n)) == math .floor(Log2(n)))


if (isPowerOfTwo(31)):
    print("Yes")
else:
    print("No")
if (isPowerOfTwo(64)):
    print("Yes")
else:
    print("No")

# Expected output:
No
Yes
# program to find whether a no is power of two | function to check if x is power of 2 ; 
def isPowerOfTwo(n):
    if (n == 0):
        return False
    while (n != 1):
        if (n % 2 != 0):
            return False
        n = n // 2
    return True


if (isPowerOfTwo(31)):
    print('Yes')
else:
    print('No')
if (isPowerOfTwo(64)):
    print('Yes')
else:
    print('No')

# Expected output:
No
Yes
# program to find whether a no is power of two | function which checks whether a number is a power of 2 ; base cases '1' is the only odd number which is a power of 2 ( 2 ^ 0 ) ; all other odd numbers are not powers of 2 ; recursive function call ; 
def powerof2(n):
    if n == 1:
        return True
    elif n % 2 != 0 or n == 0:
        return False
    return powerof2(n / 2)


if __name__ == "__main__":
    print(powerof2(64))
    print(powerof2(12))

# Expected output:
True
False
# program to find whether a no is power of two | function to check if x is power of 2 ; first x in the below expression is for the case when x is 0 ; 
def isPowerOfTwo(x):
    return (x and (not (x & (x - 1))))


if (isPowerOfTwo(31)):
    print('Yes')
else:
    print('No')
if (isPowerOfTwo(64)):
    print('Yes')
else:
    print('No')

# Expected output:
No
Yes
# find the maximum repeating number in o ( n ) time and o ( 1 ) extra space | returns maximum repeating element in arr [ 0. . n - 1 ] . the array elements are in range from 0 to k - 1 ; iterate though input array , for every element arr [ i ] , increment arr [ arr [ i ] % k ] by k ; find index of the maximum repeating element ; return index of the maximum element ; 
def maxRepeating(arr, n, k):
    for i in range(0, n):
        arr[arr[i] % k] += k
    max = arr[0]
    result = 0
    for i in range(1, n):
        if arr[i] > max:
            max = arr[i]
            result = i
    return result


arr = [2, 3, 3, 5, 3, 4, 1, 7]
n = len(arr)
k = 8
print("The maximum repeating number is", maxRepeating(arr, n, k))

# Expected output:
The maximum repeating number is 3
# range query on array whose each element is xor of index value and previous element | function return derived formula value . ; finding xor value of range [ y ... x ] ; function to solve query for l and r . ; if l or r is 0. ; finding x is divisible by 2 or not . ; 
def fun(x):
    y = (x // 4) * 4
    ans = 0
    for i in range(y, x + 1):
        ans ^= i
    return ans


def query(x):
    if (x == 0):
        return 0
    k = (x + 1) // 2
    if x % 2 == 0:
        return ((fun(k - 1) * 2) ^ (k & 1))
    else:
        return (2 * fun(k))


def allQueries(q, l, r):
    for i in range(q):
        print(query(r[i]) ^ query(l[i] - 1))


q = 3
l = [2, 2, 5]
r = [4, 8, 9]
allQueries(q, l, r)

# Expected output:
0
2
0
# minimum adjacent swaps required to sort binary array | function to find minimum swaps to sort an array of 0 s and 1 s . ; array to store count of zeroes ; count number of zeroes on right side of every one . ; count total number of swaps by adding number of zeroes on right side of every one . ; 
def findMinSwaps(arr, n):
    noOfZeroes = [0] * n
    count = 0
    noOfZeroes[n - 1] = 1 - arr[n - 1]
    for i in range(n - 2, -1, -1):
        noOfZeroes[i] = noOfZeroes[i + 1]
        if (arr[i] == 0):
            noOfZeroes[i] = noOfZeroes[i] + 1
    for i in range(0, n):
        if (arr[i] == 1):
            count = count + noOfZeroes[i]
    return count


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

# Expected output:
3
# minimum adjacent swaps required to sort binary array |  ; 
def minswaps(arr):
    count = 0
    num_unplaced_zeros = 0
    for index in range(len(arr) - 1, -1, -1):
        if arr[index] == 0:
            num_unplaced_zeros += 1
        else:
            count += num_unplaced_zeros
    return count


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

# Expected output:
3
# program to check if an array is sorted or not ( iterative and recursive ) | function that returns true if array is sorted in non - decreasing order . ; array has one or no element ; unsorted pair found ; no unsorted pair found ; 
def arraySortedOrNot(arr, n):
    if (n == 0 or n == 1):
        return True
    for i in range(1, n):
        if (arr[i - 1] > arr[i]):
            return False
    return True


arr = [20, 23, 23, 45, 78, 88]
n = len(arr)
if (arraySortedOrNot(arr, n)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# find the two numbers with odd occurrences in an unsorted array | prints two numbers that occur odd number of times . the function assumes that the array size is at least 2 and there are exactly two numbers occurring odd number of times . ; will hold xor of two odd occurring elements ; will have only single set bit of xor2 ; get the xor of all elements in arr [ ] . the xor will basically be xor of two odd occurring elements ; get one set bit in the xor2 . we get rightmost set bit in the following line as it is easy to get ; now divide elements in two sets : 1 ) the elements having the corresponding bit as 1. 2 ) the elements having the corresponding bit as 0. ; xor of first set is finally going to hold one odd occurring number x ; xor of second set is finally going to hold the other odd occurring number y ; 
def printTwoOdd(arr, size):
    xor2 = arr[0]
    set_bit_no = 0
    n = size - 2
    x, y = 0, 0
    for i in range(1, size):
        xor2 = xor2 ^ arr[i]
    set_bit_no = xor2 & ~(xor2 - 1)
    for i in range(size):
        if (arr[i] & set_bit_no):
            x = x ^ arr[i]
        else:
            y = y ^ arr[i]
    print("The two ODD elements are", x, "&", y)


arr = [4, 2, 4, 5, 2, 3, 3, 1]
arr_size = len(arr)
printTwoOdd(arr, arr_size)

# Expected output:
The two ODD elements are 5 & 1
# find a pair with the given difference | the function assumes that the array is sorted ; initialize positions of two elements ; search for a pair ; 
def findPair(arr, n):
    size = len(arr)
    i, j = 0, 1
    while i < size and j < size:
        if i != j and arr[j] - arr[i] == n:
            print("Pair found (", arr[i], ",", arr[j], ")")
            return True
        elif arr[j] - arr[i] < n:
            j += 1
        else:
            i += 1
    print("No pair found")
    return False


arr = [1, 8, 30, 40, 100]
n = 60
findPair(arr, n)

# Expected output:
Pair found ( 40 , 100 )
# find k maximum elements of array in original order | function to pr m maximum elements ; vector to store the copy of the original array ; sorting the vector in descending order . please refer below link for details ; traversing through original array and pring all those elements that are in first k of sorted vector . ; 
def printMax(arr, k, n):
    brr = arr .copy()
    brr .sort(reverse=True)
    for i in range(n):
        if (arr[i] in brr[0:k]):
            print(arr[i], end=" ")


arr = [50, 8, 45, 12, 25, 40, 84]
n = len(arr)
k = 3
printMax(arr, k, n)

# Expected output:
50 45 84
# print n smallest elements from given array in their original order | function for binary_search ; function to print smallest n numbers ; make copy of array ; sort copy array ; for each arr [ i ] find whether it is a part of n - smallest with binary search ; 
def binary_search(arr, low, high, ele):
    while low < high:
        mid = (low + high) // 2
        if arr[mid] == ele:
            return mid
        elif arr[mid] > ele:
            high = mid
        else:
            low = mid + 1
    return -1


def printSmall(arr, asize, n):
    copy_arr = arr .copy()
    copy_arr .sort()
    for i in range(asize):
        if binary_search(copy_arr, low=0, high=n, ele=arr[i]) > -1:
            print(arr[i], end=" ")


if __name__ == "__main__":
    arr = [1, 5, 8, 9, 6, 7, 3, 4, 2, 0]
    asize = len(arr)
    n = 5
    printSmall(arr, asize, n)

# Expected output:
1 3 4 2 0
# check whether arithmetic progression can be formed from the given array | returns true if a permutation of arr [ 0. . n - 1 ] can form arithmetic progression ; sort array ; after sorting , difference between consecutive elements must be same . ; 
def checkIsAP(arr, n):
    if (n == 1):
        return True
    arr .sort()
    d = arr[1] - arr[0]
    for i in range(2, n):
        if (arr[i] - arr[i - 1] != d):
            return False
    return True


arr = [20, 15, 5, 0, 10]
n = len(arr)
print("Yes")if (checkIsAP(arr, n))else print("No")

# Expected output:
Yes
# check whether arithmetic progression can be formed from the given array | returns true if a permutation of arr [ 0. . n - 1 ] can form arithmetic progression ; find the smallest and and update second smallest ; find second smallest ; check if the duplicate element found or not ; if duplicate found then return false ; find the difference between smallest and second smallest ; as we have used smallest and second smallest , so we should now only check for n - 2 elements ; 
def checkIsAP(arr, n):
    hm = {}
    smallest = float('inf')
    second_smallest = float('inf')
    for i in range(n):
        if (arr[i] < smallest):
            second_smallest = smallest
            smallest = arr[i]
        elif (arr[i] != smallest and arr[i] < second_smallest):
            second_smallest = arr[i]
        if arr[i]not in hm:
            hm[arr[i]] = 1
        else:
            return False
    diff = second_smallest - smallest
    for i in range(n - 1):
        if (second_smallest)not in hm:
            return False
        second_smallest += diff
    return True


arr = [20, 15, 5, 0, 10]
n = len(arr)
if (checkIsAP(arr, n)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# count ways of choosing a pair with maximum difference | python code to find no . of ways of choosing a pair with maximum difference ; to find minimum and maximum of the array ; to find the count of minimum and maximum elements ; count variables ; condition for all elements equal ; 
def countPairs(a, n):
    mn = +2147483647
    mx = -2147483648
    for i in range(n):
        mn = min(mn, a[i])
        mx = max(mx, a[i])
    c1 = 0
    c2 = 0
    for i in range(n):
        if (a[i] == mn):
            c1 += 1
        if (a[i] == mx):
            c2 += 1
    if (mn == mx):
        return n * (n - 1) // 2
    else:
        return c1 * c2


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

# Expected output:
4
# print all possible rotations of a given array | function to reverse array between indices s and e ; function to generate all possible rotations of array ; 
def reverse(arr, s, e):
    while s < e:
        tem = arr[s]
        arr[s] = arr[e]
        arr[e] = tem
        s = s + 1
        e = e - 1


def fun(arr, k):
    n = len(arr) - 1
    v = n - k
    if v >= 0:
        reverse(arr, 0, v)
        reverse(arr, v + 1, n)
        reverse(arr, 0, n)
        return arr


arr = [1, 2, 3, 4]
for i in range(0, len(arr)):
    count = 0
    p = fun(arr, i)
    print(p, end=" ")

# Expected output:
[1, 2, 3, 4] [4, 1, 2, 3] [2, 3, 4, 1] [3, 4, 1, 2]
# find array sum using bitwise or after splitting given array in two halves after k circular shifts | python3 program to find bitwise or of two equal halves of an array after performing k right circular shifts ; array for storing the segment tree ; function to build the segment tree ; function to return the or of elements in the range [ l , r ] ; check for out of bound condition ; find middle of the range ; recurse for all the elements in array ; function to find the or sum ; function to build the segment tree ; loop to handle q queries ; effective number of right circular shifts ; or of second half of the array [ n / 2 - i , n - 1 - i ] ; or of first half of the array [ n - i , n - 1 ] or [ 0 , n / 2 - 1 - i ] ; print final answer to the query ; 

MAX = 100005

seg = [0] * (4 * MAX)


def build(node, l, r, a):

    if (l == r):
        seg[node] = a[l]

    else:
        mid = (l + r) // 2

        build(2 * node, l, mid, a)
        build(2 * node + 1, mid + 1, r, a)

        seg[node] = (seg[2 * node] |
                     seg[2 * node + 1])


def query(node, l, r, start, end, a):
    if (l > end or r < start):
        return 0

    if (start <= l and r <= end):
        return seg[node]
    mid = (l + r) // 2
    return ((query(2 * node, l, mid,
                   start, end, a)) |
            (query(2 * node + 1, mid + 1,
                   r, start, end, a)))


def orsum(a, n, q, k):
    build(1, 0, n - 1, a)
    for j in range(q):
        i = k[j] % (n // 2)
        sec = query(1, 0, n - 1, n // 2 - i,
                    n - i - 1, a)
        first = (query(1, 0, n - 1, 0,
                       n // 2 -
                       1 - i, a) |
                 query(1, 0, n - 1,
                       n - i,
                       n - 1, a))

        temp = sec + first
        print(temp)


if __name__ == "__main__":
    a = [7, 44, 19, 86, 65, 39, 75, 101]
    n = len(a)
    q = 2
    k = [4, 2]
    orsum(a, n, q, k)

# Expected output:
238
230
# maximize count of corresponding same elements in given arrays by rotation | function that prints maximum equal elements ; list to store the index of elements of array b ; storing the positions of array b ; frequency array to keep count of elements with similar difference in distances ; iterate through all element in arr1 [ ] ; calculate number of shift required to make current element equal ; if d is less than 0 ; store the frequency of current diff ; compute the maximum frequency stored ; printing the maximum number of equal elements ; 
def maximumEqual(a, b, n):
    store = [0] * 10 ** 5
    for i in range(n):
        store[b[i]] = i + 1
    ans = [0] * 10 ** 5
    for i in range(n):
        d = abs(store[a[i]] - (i + 1))
        if (store[a[i]] < i + 1):
            d = n - d
        ans[d] += 1
    finalans = 0
    for i in range(10 ** 5):
        finalans = max(finalans, ans[i])
    print(finalans)


if __name__ == '__main__':
    A = [6, 7, 3, 9, 5]
    B = [7, 3, 9, 5, 6]
    size = len(A)
    maximumEqual(A, B, size)

# Expected output:
5
# print array after it is right rotated k times | function to rightrotate array ; if rotation is greater than size of array ; printing rightmost kth elements ; prints array after ' k ' elements ; 
def RightRotate(a, n, k):
    k = k % n
    for i in range(0, n):
        if (i < k):
            print(a[n + i - k], end=" ")
        else:
            print(a[i - k], end=" ")
    print("")


Array = [1, 2, 3, 4, 5]
N = len(Array)
K = 2
RightRotate(Array, N, K)

# Expected output:
4 5 1 2 3
# find range value of the expression | function to return the value of the given expression ; value of the first term ; value of the last term ; 
def get(L, R):
    x = 1.0 / L
    y = 1.0 / (R + 1.0)
    return (x - y)


if __name__ == "__main__":
    L = 6
    R = 12
    ans = get(L, R)
    print(round(ans, 2))

# Expected output:
0.09
# minimum deletions required such that any number x will occur exactly x times | function to return the minimum deletions required ; to store the frequency of the array elements ; store frequency of each element ; to store the minimum deletions required ; value ; it 's frequency ; if number less than or equal to it 's frequency ; delete extra occurrences ; delete every occurrence of x ; 
def MinDeletion(a, n):
    map = dict .fromkeys(a, 0)
    for i in range(n):
        map[a[i]] += 1
    ans = 0
    for key, value in map .items():
        x = key
        frequency = value
        if (x <= frequency):
            ans += (frequency - x)
        else:
            ans += frequency
    return ans


if __name__ == "__main__":
    a = [2, 3, 2, 3, 4, 4, 4, 4, 5]
    n = len(a)
    print(MinDeletion(a, n))

# Expected output:
3
# concatenate strings in any order to get maximum number of " ab " | function to find maximum number of abs ; variable a , b , ab for count strings that end with ' a ' but not end with ' b ' , ' b ' but does not end with ' a ' and ' b ' and ends with ' a ' respectively . ; ' ab ' is already present in string before concatenate them ; count of strings that begins with ' b ' and ends with 'a ; count of strings that begins with ' b ' but does not end with 'a ; count of strings that ends with ' a ' but not end with 'b ; updating the value of ans and add extra count of 'ab ; 
def maxCountAB(s, n):
    A = 0
    B = 0
    BA = 0
    ans = 0

    for i in range(n):
        S = s[i]
        L = len(S)
        for j in range(L-1):
            if (S[j] == 'A' and S[j + 1] == 'B'):
                ans += 1
        if (S[0] == 'B' and S[L - 1] == 'A'):
            BA += 1
        elif (S[0] == 'B'):
            B += 1
        elif (S[L - 1] == 'A'):
            A += 1
    if (BA == 0):
        ans += min(B, A)
    elif (A + B == 0):
        ans += BA - 1
    else:
        ans += BA + min(B, A)
    return ans


if __name__ == '__main__':
    s = ["ABCA", "BOOK", "BAND"]

    n = len(s)

    print(maxCountAB(s, n))

# Expected output:
2
# minimum operations to make sum of neighbouring elements <= x | function to return the minimum number of operations required ; to store total operations required ; first make all elements equal to x which are currenctly greater ; left scan the array ; update the current element such that neighbouring sum is < x ; 
def MinOperations(n, x, arr):
    total = 0
    for i in range(n):
        if (arr[i] > x):
            difference = arr[i] - x
            total = total + difference
            arr[i] = x
    for i in range(n):
        LeftNeigbouringSum = arr[i] + arr[i - 1]
        if (LeftNeigbouringSum > x):
            current_diff = LeftNeigbouringSum - x
            arr[i] = max(0, arr[i] - current_diff)
            total = total + current_diff
    return total


X = 1
arr = [1, 6, 1, 2, 0, 4]
N = len(arr)
print(MinOperations(N, X, arr))

# Expected output:
11
# find the repeating and the missing number using two equations | python3 implementation of the approach ; function to print the required numbers ; sum of first n natural numbers ; sum of squares of first n natural numbers ; to store the sum and sum of squares of the array elements ; 

import math


def findNumbers(arr, n):
    sumN = (n * (n + 1)) / 2
    sumSqN = (n * (n + 1) * (2 * n + 1)) / 6
    sum = 0
    sumSq = 0
    for i in range(0, n):
        sum = sum + arr[i]
        sumSq = sumSq + (math .pow(arr[i], 2))
    B = (((sumSq - sumSqN) / (sum - sumN)) + sumN - sum) / 2
    A = sum - sumN + B
    print("A = ", int(A))
    print("B = ", int(B))


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

# Expected output:
A =  2
B =  5
# lexicographically smallest string with given string as prefix | function to find the whether the string temp starts with str or not ; base case ; check for the corresponding characters in temp & str ; function to find lexicographic smallest string consisting of the string str as prefix ; sort the given array string arr [ ] ; if the i - th string contains given string as a prefix , then print the result ; if no string exists then return " - 1" ; 
def is_prefix(temp, str):
    if (len(temp) < len(str)):
        return 0
    else:
        for i in range(len(str)):
            if (str[i] != temp[i]):
                return 0
        return 1


def lexicographicallyString(input, n, str):
    input .sort()
    for i in range(n):
        temp = input[i]
        if (is_prefix(temp, str)):
            return temp
    return "-1"


if __name__ == '__main__':
    arr = ["apple", "appe", "apl", "aapl", "appax"]
    S = "app"
    N = 5
    print(lexicographicallyString(arr, N, S))

# Expected output:
appax
# rearrange array to find k using binary search algorithm without sorting | function to rearrange the array ; stores the rearranged array ; stores whether the arrangement is possible or not ; update k with the position of k ; stores all elements lesser than and greater than in vector smaller and greater respectively ; traverse the array arr [ ] ; if arr [ i ] is less than arr [ k ] ; else ; iterate unil low is less than or equal to high ; stores mid point ; if mid is equal to k ; if mid is less than k ; if mid is greater than k ; if f is - 1 ; iterate in the range [ 1 , n ] ; if ans [ i ] is equal to - 1 ; print the rearranged array ; 
def Rearrange(arr, K, N):
    ans = [0] * (N + 1)
    f = -1
    for i in range(N):
        ans[i] = -1
    K = arr .index(K)
    smaller = []
    greater = []
    for i in range(N):
        if (arr[i] < arr[K]):
            smaller .append(arr[i])
        elif (arr[i] > arr[K]):
            greater .append(arr[i])
    low = 0
    high = N - 1
    while (low <= high):
        mid = (low + high) // 2
        if (mid == K):
            ans[mid] = arr[K]
            f = 1
            break
        elif (mid < K):
            if (len(smaller) == 0):
                break
            ans[mid] = smaller[-1]
            smaller .pop()
            low = mid + 1
        else:
            if (len(greater) == 0):
                break
            ans[mid] = greater[-1]
            greater .pop()
            high = mid - 1
    if (f == -1):
        print(-1)
        return
    for i in range(N):
        if (ans[i] == -1):
            if (len(smaller)):
                ans[i] = smaller[-1]
                smaller .pop()
            elif (len(greater)):
                ans[i] = greater[-1]
                greater .pop()
    for i in range(N):
        print(ans[i], end=" ")
    print()


if __name__ == "__main__":
    arr = [10, 7, 2, 5, 3, 8]
    K = 7
    N = len(arr)
    Rearrange(arr, K, N)

# Expected output:
3 7 8 5 2 10
# minimize k to let person a consume at least ceil ( n / ( m + 1 ) ) candies based on given rules | python 3 program for the above approach ; function to find minimum value of k such that the first person gets at least ( n / ( m + 1 ) ) candies ; find the minimum required value of candies for the first person ; iterate k from [ 1 , n ] ; total number of candies ; candies taken by person 1 ; candies taken by 1 st person is minimum of k and candies left ; traverse the array arr [ ] ; amount consumed by the person j ; update the number of candies ; good share of candies achieved ; 

import math


def minimumK(arr,  M, N):
    good = math.ceil((N * 1.0) / ((M + 1) * 1.0))
    for i in range(1, N + 1):
        K = i
        candies = N
        taken = 0

        while (candies > 0):
            taken += min(K, candies)
            candies -= min(K, candies)
            for j in range(M):
                consume = (arr[j]
                           * candies) / 100
                candies -= consume
        if (taken >= good):
            print(i)
            return


if __name__ == "__main__":
    N = 13
    M = 1
    arr = [50]
    minimumK(arr, M, N)

# Expected output:
3