giulio98/xlcost-single-prompt huggingface dataset:
# sum of bitwise and of all unordered triplets of an array | function to calculate sum of bitwise and of all unordered triplets from a given array such that ( i < j < k ) ; stores the resultant sum of bitwise and of all triplets ; traverse over all the bits ; count number of elements with the current bit set ; there are ( cnt ) c ( 3 ) numbers with the current bit set and each triplet contributes 2 ^ bit to the result ; return the resultant sum ; 
def tripletAndSum(arr, n):
    ans = 0
    for bit in range(32):
        cnt = 0
        for i in range(n):
            if (arr[i] & (1 << bit)):
                cnt += 1
        ans += (1 << bit) * cnt * (cnt - 1) * (cnt - 2) // 6
    return ans


arr = [3, 5, 4, 7]
N = len(arr)
print(tripletAndSum(arr, N))

# Expected output:
5
# lexicographically smallest permutation of length 2 n that can be obtained from an n | python3 program for the above approach ; function to find the lexicographically smallest permutation of length 2 * n satisfying the given conditions ; stores if i - th element is placed at odd position or not ; traverse the array ; mark arr [ i ] true ; stores all the elements not placed at odd positions ; iterate in the range [ 1 , 2 * n ] ; if w [ i ] is not marked ; stores whether it is possible to obtain the required permutation or not ; stores the permutation ; traverse the array arr [ ] ; finds the iterator of the smallest number greater than the arr [ i ] ; if it is s . end ( ) ; mark found false ; push arr [ i ] and * it into the array ; erase the current element from the set ; if found is not marked ; otherwise , ; print the permutation ; 

from bisect import bisect_left


def smallestPermutation(arr, N):
    w = [False for i in range(2 * N + 1)]
    for i in range(N):
        w[arr[i]] = True
    S = set()
    for i in range(1, 2 * N + 1, 1):
        if (w[i] == False):
            S .add(i)
    found = True
    P = []
    S = list(S)
    for i in range(N):
        it = bisect_left(S, arr[i])
        if (it == -1):
            found = False
            break
        P .append(arr[i])
        P .append(S[it])
        S .remove(S[it])
    if (found == False):
        print("-1")
    else:
        for i in range(2 * N):
            print(P[i], end=" ")


if __name__ == '__main__':
    arr = [4, 1, 3]
    N = len(arr)
    smallestPermutation(arr, N)

# Expected output:
4 5 1 2 3 6
# maximum sum of a subsequence having difference between their indices equal to the difference between their values | function to find the maximum sum of a subsequence having difference between indices equal to difference in their values ; stores the maximum sum ; stores the value for each a [ i ] - i ; traverse the array ; update the value in map ; update the answer ; finally , print the answer ; 
def maximumSubsequenceSum(A, N):
    ans = 0
    mp = {}
    for i in range(N):
        if (A[i] - i in mp):
            mp[A[i] - i] += A[i]
        else:
            mp[A[i] - i] = A[i]
        ans = max(ans, mp[A[i] - i])
    print(ans)


if __name__ == '__main__':
    A = [10, 7, 1, 9, 10, 1]
    N = len(A)
    maximumSubsequenceSum(A, N)

# Expected output:
26
# find the nearest perfect square for each element of the array | function to find the nearest perfect square for every element in the given array import the math module ; traverse the array ; calculate square root of current element ; calculate perfect square ; find the nearest ; 

import math


def nearestPerfectSquare(arr, N):
    for i in range(0, N):
        sr = math .floor(math .sqrt(arr[i]))
        a = sr * sr
        b = (sr + 1) * (sr + 1)
        if ((arr[i] - a) < (b - arr[i])):
            print(a, end=" ")
        else:
            print(b, end=" ")


arr = [5, 2, 7, 13]
N = len(arr)
nearestPerfectSquare(arr, N)

# Expected output:
4 1 9 16
# count of sets possible using integers from a range [ 2 , n ] using given operations that are in equivalence relation | python3 program for the above approach ; sieve of eratosthenes to find primes less than or equal to n ; function to find number of sets ; handle base case ; set which contains less than or equal to n / 2 ; number greater than n / 2 and are prime increment it by 1 ; if the number is prime increment answer by 1 ; 

prime = [True] * 100001


def SieveOfEratosthenes(n):
    global prime
    for p in range(2, n + 1):
        if p * p > n:
            break
        if (prime[p]):
            for i in range(p * p, n + 1, p):
                prime[i] = False


def NumberofSets(N):
    SieveOfEratosthenes(N)
    if (N == 2):
        print(1)
    elif (N == 3):
        print(2)
    else:
        ans = 1
        for i in range(N // 2, N + 1):
            if (prime[i]):
                ans += 1
        print(ans)


if __name__ == '__main__':
    N = 9
    NumberofSets(N)

# Expected output:
3
# absolute difference between floor of array sum divided by x and floor sum of every array element when divided by x | function to find absolute difference between the two sum values ; variable to store total sum ; variable to store sum of a [ i ] / x ; traverse the array ; update totalsum ; update perelementsum ; floor of total sum divided by x ; return the absolute difference ; 
def floorDifference(A, N, X):
    totalSum = 0
    perElementSum = 0
    for i in range(N):
        totalSum += A[i]
        perElementSum += A[i] // X
    totalFloorSum = totalSum // X
    return abs(totalFloorSum - perElementSum)


if __name__ == '__main__':
    A = [1, 2, 3, 4, 5, 6]
    X = 4
    N = len(A)
    print(floorDifference(A, N, X))

# Expected output:
2
# convert a number from base a to base b | function to return ascii value of a character ; function to convert a number from given base to decimal number ; stores the length of the string ; initialize power of base ; initialize result ; decimal equivalent is strr [ len - 1 ] * 1 + strr [ len - 2 ] * base + strr [ len - 3 ] * ( base ^ 2 ) + ... ; a digit in input number must be less than number 's base ; update num ; update power ; function to return equivalent character of a given value ; function to convert a given decimal number to a given base ; store the result ; repeatedly divide inputnum by base and take remainder ; update res ; update inputnum ; reverse the result ; function to convert a given number from a base to another base ; convert the number from base a to decimal ; convert the number from decimal to base b ; prthe result ; 
def val(c):
    if (c >= '0' and c <= '9'):
        return ord(c) - 48
    else:
        return ord(c) - 65 + 10


def toDeci(strr, base):
    lenn = len(strr)
    power = 1
    num = 0
    for i in range(lenn - 1, -1, -1):
        if (val(strr[i]) >= base):
            print("Invalid Number")
            return -1
        num += val(strr[i]) * power
        power = power * base
    return num


def reVal(num):
    if (num >= 0 and num <= 9):
        return chr(num + 48)
    else:
        return chr(num - 10 + 65)


def fromDeci(base, inputNum):
    res = ""
    while (inputNum > 0):
        res += reVal(inputNum % base)
        inputNum //= base
    res = res[::-1]
    return res


def convertBase(s, a, b):
    num = toDeci(s, a)
    ans = fromDeci(b, num)
    print(ans)


s = "10B"
a = 16
b = 10
convertBase(s, a, b)

# Expected output:
267
# prefix factorials of a prefix sum array | function to find the factorial of a number n ; base case ; find the factorial recursively ; function to find the prefix factorial array ; find the prefix sum array ; find the factorials of each array element ; print the resultant array ; 
def fact(N):
    if (N == 1 or N == 0):
        return 1
    return N * fact(N - 1)


def prefixFactorialArray(arr, N):
    for i in range(1, N):
        arr[i] += arr[i - 1]
    for i in range(N):
        arr[i] = fact(arr[i])
    for i in range(N):
        print(arr[i], end=" ")


if __name__ == "__main__":
    arr = [1, 2, 3, 4]
    N = len(arr)
    prefixFactorialArray(arr, N)

# Expected output:
1 6 720 3628800
# mean of fourth powers of first n natural numbers | function to find the average of the fourth power of first n natural numbers ; store the resultant average calculated using formula ; return the average ; 
def findAverage(N):
    avg = ((6 * N * N * N * N) + (15 * N * N * N) + (10 * N * N) - 1) / 30
    return avg


N = 3
print(round(findAverage(N), 4))

# Expected output:
32.6667
# modify array by removing ( arr [ i ] + arr [ i + 1 ] ) th element exactly k times | function to modify array by removing every k - th element from the array ; check if current element is the k - th element ; stores the elements after removing every kth element ; append the current element if it is not k - th element ; return the new array after removing every k - th element ; function to print the array ; traverse the array l [ ] ; function to print the array after performing the given operations exactly k times ; store first n natural numbers ; iterate over the range [ 0 , k - 1 ] ; store sums of the two consecutive terms ; remove every p - th element from the array ; increment x by 1 for the next iteration ; print the resultant array ; 
def removeEveryKth(l, k):
    for i in range(0, len(l)):
        if i % k == 0:
            l[i] = 0
    arr = [0]
    for i in range(1, len(l)):
        if l[i] != 0:
            arr .append(l[i])
    return arr


def printArray(l):
    for i in range(1, len(l)):
        print(l[i], end=" ")
    print()


def printSequence(n, k):
    l = [int(i)for i in range(0, n + 1)]
    x = 1
    for i in range(0, k):
        p = l[x] + l[x + 1]
        l = removeEveryKth(l, p)
        x += 1
    printArray(l)


N = 8
K = 2
printSequence(N, K)

# Expected output:
1 2 4 5 7
# minimum number of bits of array elements required to be flipped to make all array elements equal | function to count minimum number of bits required to be flipped to make all array elements equal ; stores the count of unset bits ; stores the count of set bits ; traverse the array ; traverse the bit of arr [ i ] ; if current bit is set ; increment fre1 [ j ] ; otherwise ; increment fre0 [ j ] ; right shift x by 1 ; stores the count of total moves ; traverse the range [ 0 , 32 ] ; update the value of ans ; return the minimum number of flips required ; 
def makeEqual(arr, n):
    fre0 = [0] * 33
    fre1 = [0] * 33
    for i in range(n):
        x = arr[i]
        for j in range(33):
            if (x & 1):
                fre1[j] += 1
            else:
                fre0[j] += 1
            x = x >> 1
    ans = 0
    for i in range(33):
        ans += min(fre0[i], fre1[i])
    return ans


if __name__ == '__main__':
    arr = [3, 5]
    N = len(arr)
    print(makeEqual(arr, N))

# Expected output:
2
# sum of array elements possible by appending arr [ i ] / k to the end of the array k times for array elements divisible by k | function to calculate sum of array elements after adding arr [ i ] / k to the end of the array if arr [ i ] is divisible by k ; stores the sum of the array ; traverse the array arr [ ] ; traverse the vector ; if v [ i ] is divisible by k ; iterate over the range [ 0 , k ] ; update v ; otherwise ; traverse the vector v ; return the sum of the updated array ; 
def summ(arr, N, K):
    sum = 4
    v = [i for i in arr]
    for i in range(len(v)):
        if (v[i] % K == 0):
            x = v[i] // K
            for j in range(K):
                v .append(x)
        else:
            break
    for i in range(len(v)):
        sum = sum + v[i]
    return sum


if __name__ == '__main__':
    arr = [4, 6, 8, 2]
    K = 2
    N = len(arr)
    print(summ(arr, N, K))

# Expected output:
44
# check if sum of arr [ i ] / j for all possible pairs ( i , j ) in an array is 0 or not | function to check if sum of all values of ( arr [ i ] / j ) for all 0 < i <= j < ( n - 1 ) is 0 or not ; stores the required sum ; traverse the array ; if the sum is equal to 0 ; otherwise ; 
def check(arr, N):
    sum = 0
    for i in range(N):
        sum += arr[i]
    if (sum == 0):
        print("Yes")
    else:
        print("No")


if __name__ == '__main__':
    arr = [1, -1, 3, -2, -1]
    N = len(arr)
    check(arr, N)

# Expected output:
Yes
# program to calculate expected increase in price p after n consecutive days | function to find the increased value of p after n days ; expected value of the number p after n days ; print the expected value ; 
def expectedValue(P, a, b, N):
    expValue = P + (N * 0.5 * (a + b))
    print(int(expValue))


if __name__ == '__main__':
    P = 3000
    a = 20
    b = 10
    N = 30
    expectedValue(P, a, b, N)

# Expected output:
3450
# find the index in a circular array from which prefix sum is always non | function to find the starting index of the given circular array prefix sum array is non negative ; stores the sum of the array ; stores the starting index ; stores the minimum prefix sum of a [ 0. . i ] ; traverse the array ; update the value of sum ; if sum is less than minimum ; update the min as the value of prefix sum ; update starting index ; otherwise no such index is possible ; 

import sys


def startingPoint(A, N):
    sum = 0
    startingindex = 0
    min = sys .maxsize
    for i in range(0, N):
        sum += A[i]
        if (sum < min):
            min = sum
            startingindex = i + 1
    if (sum < 0):
        return -1
    return startingindex % N


arr = [3, -6, 7, -4, -4, 6, -1]
N = len(arr)
print(startingPoint(arr, N))

# Expected output:
5
# modify array by replacing elements with the nearest power of its previous or next element | python3 program for the above approach ; function to calculate the power of y which is nearest to x ; base case ; stores the logarithmic value of x with base y ; function to replace each array element by the nearest power of its previous or next element ; stores the previous and next element ; traverse the array ; calculate nearest power for previous and next elements ; replacing the array values ; print the updated array ; 

import math


def nearestPow(x, y):
    if y == 1:
        return 1
    k = int(math .log(x, y))
    if abs(y ** k - x) < abs(y ** (k + 1) - x):
        return y ** k
    return y ** (k + 1)


def replacebyNearestPower(arr):
    prev = arr[-1]
    lastNext = arr[0]
    for i in range(len(arr)):
        temp = arr[i]
        if i == len(arr) - 1:
            next = lastNext
        else:
            next = arr[(i + 1) % len(arr)]
        prevPow = nearestPow(arr[i], prev)
        nextPow = nearestPow(arr[i], next)
        if abs(arr[i] - prevPow) < abs(arr[i] - nextPow):
            arr[i] = prevPow
        else:
            arr[i] = nextPow
        prev = temp
    print(arr)


arr = [2, 3, 4, 1, 2]
replacebyNearestPower(arr)

# Expected output:
[2, 4, 3, 1, 2]
# check if sum of array can be made equal to x by removing either the first or last digits of every array element | utility function to check if the sum of the array elements can be made equal to x by removing either the first or last digits of every array element ; base case ; convert arr [ i ] to string ; remove last digit ; remove first digit ; recursive function call ; function to check if sum of given array can be made equal to x or not ; 
def makeSumX(arr, X, S, i):
    if i == len(arr):
        return S == X
    a = str(arr[i])
    l = int(a[:-1])
    r = int(a[1:])
    x = makeSumX(arr, X, S + l, i + 1)
    y = makeSumX(arr, X, S + r, i + 1)
    return x | y


def Check(arr, X):
    if (makeSumX(arr, X, 0, 0)):
        print("Yes")
    else:
        print("No")


arr = [545, 433, 654, 23]
X = 134
Check(arr, X)

# Expected output:
Yes
# count subarrays having product equal to the power of a given prime number | python 3 program for the above approach ; function to check if y is a power of m or not ; calculate log y base m and store it in a variable with integer datatype ; calculate log y base m and store it in a variable with double datatype ; if res1 and res2 are equal , return true . otherwise , return false ; function to count the number of subarrays having product of elements equal to a power of m , where m is a prime number ; stores the count of subarrays required ; stores current sequence of consecutive array elements which are a multiple of m ; traverse the array ; if arr [ i ] is a power of m ; increment cnt ; update ans ; update cnt ; return the count of subarrays ; 

from math import log


def isPower(m, y):
    res1 = log(y) // log(m)
    res2 = log(y) // log(m)
    return (res1 == res2)


def numSub(arr, n, m):
    ans = 0
    cnt = 0
    for i in range(n):
        if (isPower(m, arr[i])):
            cnt += 1
            ans += (cnt * (cnt - 1)) // 2
        else:
            cnt = 0
    return ans


if __name__ == '__main__':
    arr = [1, 1, 1, 3]
    m = 3
    n = len(arr)
    print(numSub(arr, n, m))

# Expected output:
10
# count pairs whose bitwise and exceeds bitwise xor from a given array | python3 program to implement the above approach ; function to count pairs that satisfy the above condition ; stores the count of pairs ; stores the count of array elements having same positions of msb ; traverse the array ; stores the index of msb of array elements ; calculate number of pairs ; 

import math


def cntPairs(arr, N):
    res = 0
    bit = [0] * 32
    for i in range(N):
        pos = (int)(math .log2(arr[i]))
        bit[pos] += 1
    for i in range(32):
        res += (bit[i] * (bit[i] - 1)) // 2
    return res


if __name__ == "__main__":
    arr = [1, 2, 3, 4]
    N = len(arr)
    print(cntPairs(arr, N))

# Expected output:
1
# minimum mex from all subarrays of length k | function to return minimum mex from all k - length subarrays ; stores element from [ 1 , n + 1 ] which are not present in subarray ; store number 1 to n + 1 in set s ; find the mex of k - length subarray starting from index 0 ; find the mex of all subarrays of length k by erasing arr [ i ] and inserting arr [ i - k ] ; store first element of set ; updating the mex ; print minimum mex of all k length subarray ; 
def minimumMEX(arr, N, K):
    s = set()
    for i in range(1, N + 2, 1):
        s .add(i)
    for i in range(K):
        s .remove(arr[i])
    mex = list(s)[0]
    for i in range(K, N, 1):
        s .remove(arr[i])
        s .add(arr[i - K])
        firstElem = list(s)[0]
        mex = min(mex, firstElem)
    print(mex)


if __name__ == '__main__':
    arr = [1, 2, 3, 4, 5, 6]
    K = 3
    N = len(arr)
    minimumMEX(arr, N, K)

# Expected output:
1
# count smaller elements present in the array for each array element | function to count for each array element , the number of elements that are smaller than that element ; stores the frequencies of array elements ; traverse the array ; update frequency of arr [ i ] ; initialize sum with 0 ; compute prefix sum of the array hash [ ] ; traverse the array arr [ ] ; if current element is 0 ; print the resultant count ; 
def smallerNumbers(arr, N):
    hash = [0] * 100000
    for i in range(N):
        hash[arr[i]] += 1
    sum = 0
    for i in range(1, 100000):
        hash[i] += hash[i - 1]
    for i in range(N):
        if (arr[i] == 0):
            print("0")
            continue
        print(hash[arr[i] - 1], end=" ")


if __name__ == "__main__":
    arr = [3, 4, 1, 1, 2]
    N = len(arr)
    smallerNumbers(arr, N)

# Expected output:
3 4 0 0 2
# modulo operations in programming with negative results | function to calculate and return the remainder of a % n ; ( a / n ) implicitly gives the truncated result ; 
def truncMod(a, n):
    q = a // n
    return a - n * q


if __name__ == '__main__':
    a = 9
    b = 4
    print(a, "%", b, "=", truncMod(a, b))
    a = -9
    b = 4
    print(a, "%", b, "=", truncMod(a, b))
    a = 9
    b = -4
    print(a, "%", b, "=", truncMod(a, b))
    a = -9
    b = -4
    print(a, "%", b, "=", truncMod(a, b))

# Expected output:
9 % 4 = 1
-9 % 4 = 3
9 % -4 = -3
-9 % -4 = -1
# count number of pairs ( i , j ) from an array such that arr [ i ] * j = arr [ j ] * i | python3 program for the above approach ; function to count pairs from an array satisfying given conditions ; stores the total count of pairs ; stores count of a [ i ] / i ; traverse the array ; updating count ; update frequency in the map ; print count of pairs ; 

from collections import defaultdict


def countPairs(arr, N):
    count = 0
    mp = defaultdict(int)
    for i in range(N):
        val = 1.0 * arr[i]
        idx = 1.0 * (i + 1)
        count += mp[val / idx]
        mp[val / idx] += 1
    print(count)


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

# Expected output:
2
# count subsequences having odd bitwise xor values from an array | function to count the subsequences having odd bitwise xor value ; stores count of odd elements ; stores count of even elements ; traverse the array a [ ] ; if el is odd ; if count of odd elements is 0 ; 
def countSubsequences(A):
    odd = 0
    even = 0
    for el in A:
        if (el % 2 == 1):
            odd += 1
        else:
            even += 1
    if (odd == 0):
        print(0)
    else:
        print(1 << len(A) - 1)


if __name__ == "__main__":
    A = [1, 3, 4]
    countSubsequences(A)

# Expected output:
4
# maximum subarray product modulo m | function to find maximum subarray product modulo m and minimum length of the subarray ; stores maximum subarray product modulo m and minimum length of the subarray ; stores the minimum length of subarray having maximum product ; traverse the array ; stores the product of a subarray ; calculate subarray whose start index is i ; multiply product by arr [ i ] ; if product greater than ans ; update ans ; update length ; print maximum subarray product mod m ; print minimum length of subarray having maximum product ; 
def maxModProdSubarr(arr, n, M):
    ans = 0
    length = n
    for i in range(n):
        product = 1
        for j in range(i, n, 1):
            product = (product * arr[i]) % M
            if (product > ans):
                ans = product
                if (length > j - i + 1):
                    length = j - i + 1
    print("Maximum subarray product is", ans)
    print("Minimum length of the maximum product subarray is", length)


if __name__ == '__main__':
    arr = [2, 3, 4, 2]
    N = len(arr)
    M = 5
    maxModProdSubarr(arr, N, M)

# Expected output:
Maximum subarray product is 4
Minimum length of the maximum product subarray is 1
# number of co | python3 program for the above approach ; function to check whether given integers are co - prime or not ; utility function to count number of co - prime pairs ; traverse the array ; if co - prime ; increment count ; return count ; function to count number of co - prime pairs ; stores digits in string form ; sort the list ; keep two copies of list l ; generate 2 digit numbers using d1 and d2 ; if current number does not exceed n ; stores length of list ; stores number of co - prime pairs ; print number of co - prime pairs ; 

from copy import deepcopy
import math


def coprime(a, b):
    return (math .gcd(a, b)) == 1


def numOfPairs(arr, N):
    count = 0
    for i in range(0, N - 1):
        for j in range(i + 1, N):
            if (coprime(int(arr[i]), int(arr[j]))):
                count = count + 1
    return count


def noOfCoPrimePairs(N, d1, d2):
    l = []
    l .append(str(d1))
    l .append(str(d2))
    l .sort()
    if int(N) < int(l[1]):
        return 0
    total = temp2 = deepcopy(l)
    flag = 0
    temp3 = []
    while len(l[0]) < 10:
        for i in range(len(l)):
            for j in range(2):
                if int(l[i] + temp2[j]) > int(N):
                    flag = 1
                    break
                total .append(l[i] + temp2[j])
                temp3 .append(l[i] + temp2[j])
            if flag == 1:
                break
        if flag == 1:
            break
        l = deepcopy(temp3)
        temp3 = []
    lenOfTotal = len(total)
    ans = numOfPairs(total, lenOfTotal)
    print(ans)


if __name__ == "__main__":
    N = 30
    d1 = 2
    d2 = 3
    noOfCoPrimePairs(N, d1, d2)

# Expected output:
5