giulio98/xlcost-single-prompt huggingface dataset:
# lcm of given array elements | recursive function to return gcd of a and b ; recursive implementation ; lcm ( a , b ) = ( a * b / gcd ( a , b ) ) ; 
def __gcd(a, b):
    if (a == 0):
        return b
    return __gcd(b % a, a)


def LcmOfArray(arr, idx):
    if (idx == len(arr) - 1):
        return arr[idx]
    a = arr[idx]
    b = LcmOfArray(arr, idx + 1)
    return int(a * b / __gcd(a, b))


arr = [1, 2, 8, 3]
print(LcmOfArray(arr, 0))
arr = [2, 7, 3, 9, 4]
print(LcmOfArray(arr, 0))

# Expected output:
24
252
# Check if a number is a power of another number | Returns true if y is a power of x ; The only power of 1 is 1 itself ; Repeatedly compute power of x ; Check if power of x becomes y ; check the result for true / false and print
def isPower(x, y):
    if (x == 1):
        return (y == 1)
    pow = 1
    while (pow < y):
        pow = pow * x
    return (pow == y)


if (isPower(10, 1)):
    print(1)
else:
    print(0)
if (isPower(1, 20)):
    print(1)
else:
    print(0)
if (isPower(2, 128)):
    print(1)
else:
    print(0)
if (isPower(2, 30)):
    print(1)
else:
    print(0)

# Expected output:
1
0
1
0
# number of perfect squares between two given numbers | an efficient method to count squares between a and b ; an efficient solution to count square between a and b ; 

import math


def CountSquares(a, b):
    return (math .floor(math .sqrt(b)) - math .ceil(math .sqrt(a)) + 1)


a = 9
b = 25
print("Count of squares is:", int(CountSquares(a, b)))

# Expected output:
Count of squares is: 3
# check if count of divisors is even or odd | naive solution to find if count of divisors is even or odd ; function to count the divisors ; initialize count of divisors ; note that this loop runs till square root ; if divisors are equal , increment count by one otherwise increment count by 2 ; 

import math


def countDivisors(n):
    count = 0
    for i in range(1, (int)(math .sqrt(n)) + 2):
        if (n % i == 0):
            if (n // i == i):
                count = count + 1
            else:
                count = count + 2
    if (count % 2 == 0):
        print("Even")
    else:
        print("Odd")


print("The count of divisor: ")
countDivisors(10)

# Expected output:
The count of divisor: 
Even
# gray to binary and binary to gray conversion | python3 code for above approach ; 
def greyConverter(n):
    return n ^ (n >> 1)


n = 3
print(greyConverter(n))
n = 9
print(greyConverter(n))

# Expected output:
2
13
# compute n ! under modulo p | returns largest power of p that divides n ! ; initialize result ; calculate x = n / p + n / ( p ^ 2 ) + n / ( p ^ 3 ) + ... . ; utility function to do modular exponentiation . it returns ( x ^ y ) % p ; initialize result update x if it is more than or equal to p ; if y is odd , multiply x with result ; y must be even now y = y >> 1 y = y / 2 ; returns n ! % p ; use sieve of eratosthenes to find all primes smaller than n ; consider all primes found by sieve ; find the largest power of prime ' i ' that divides n ; multiply result with ( i ^ k ) % p ; 
def largestPower(n, p):
    x = 0

    while (n):
        n //= p
        x += n
    return x


def power(x, y, p):
    res = 1
    x = x % p
    while (y > 0):
        if (y & 1):
            res = (res * x) % p
        y = y >> 1
        x = (x * x) % p

    return res


def modFact(n, p):

    if (n >= p):
        return 0

    res = 1
    isPrime = [1] * (n + 1)
    i = 2
    while (i * i <= n):
        if (isPrime[i]):
            for j in range(2 * i, n, i):
                isPrime[j] = 0
        i += 1
    for i in range(2, n):
        if (isPrime[i]):
            k = largestPower(n, i)
            res = (res * power(i, k, p)) % p

    return res


if __name__ == "__main__":
    n = 25
    p = 29
    print(modFact(n, p))

# Expected output:
5
# count number of squares in a rectangle | returns count of all squares in a rectangle of size m x n ; if n is smaller , swap m and n ; now n is greater dimension , apply formula ; 
def countSquares(m, n):
    if (n < m):
        temp = m
        m = n
        n = temp
    return ((m * (m + 1) * (2 * m + 1) / 6 + (n - m) * m * (m + 1) / 2))


if __name__ == '__main__':
    m = 4
    n = 3
    print("Count of squares is ", countSquares(m, n))

# Expected output:
Count of squares is  20.0
# count factorial numbers in a given range | function to count factorial ; find the first factorial number ' fact ' greater than or equal to 'low ; count factorial numbers in range [ low , high ] ; return the count ; 
def countFact(low, high):
    fact = 1
    x = 1
    while (fact < low):
        fact = fact * x
        x += 1
    res = 0
    while (fact <= high):
        res += 1
        fact = fact * x
        x += 1
    return res


print("Count is ", countFact(2, 720))

# Expected output:
Count is  5
# find number of days between two given dates | a date has day ' d ' , month ' m ' and year 'y ; to store number of days in all months from january to dec . ; this function counts number of leap years before the given date ; check if the current year needs to be considered for the count of leap years or not ; an year is a leap year if it is a multiple of 4 , multiple of 400 and not a multiple of 100. ; this function returns number of days between two given dates ; initialize count using years and day ; add days for months in given date ; since every leap year is of 366 days , add a day for every leap year ; similarly , count total number of days before 'dt2 ; return difference between two counts ; 


class Date:
    def __init__(self, d, m, y):
        self.d = d
        self.m = m
        self.y = y


monthDays = [31, 28, 31, 30, 31, 30,
             31, 31, 30, 31, 30, 31]


def countLeapYears(d):

    years = d.y
    if (d.m <= 2):
        years -= 1
    ans = int(years / 4)
    ans -= int(years / 100)
    ans += int(years / 400)
    return ans


def getDifference(dt1, dt2):
    n1 = dt1.y * 365 + dt1.d
    for i in range(0, dt1.m - 1):
        n1 += monthDays[i]
    n1 += countLeapYears(dt1)
    n2 = dt2.y * 365 + dt2.d
    for i in range(0, dt2.m - 1):
        n2 += monthDays[i]
    n2 += countLeapYears(dt2)

    return (n2 - n1)


dt1 = Date(1, 9, 2014)
dt2 = Date(3, 9, 2020)
print("Difference between two dates is", getDifference(dt1, dt2))

# Expected output:
Difference between two dates is 2194
# find length of period in decimal value of 1 / n | function to find length of period in 1 / n ; find the ( n + 1 ) th remainder after decimal point in value of 1 / n ; store ( n + 1 ) th remainder ; count the number of remainders before next occurrence of ( n + 1 ) ' th ▁ remainder ▁ ' d ; 
def getPeriod(n):
    rem = 1
    for i in range(1, n + 2):
        rem = (10 * rem) % n
    d = rem
    count = 0
    rem = (10 * rem) % n
    count += 1
    while rem != d:
        rem = (10 * rem) % n
        count += 1
    return count


if __name__ == "__main__":
    print(getPeriod(3))
    print(getPeriod(7))

# Expected output:
1
6
# replace all â €˜ 0 â €™ with â €˜ 5 â €™ in an input integer |  ; returns the number to be added to the input to replace all zeroes with five ; amount to be added ; unit decimal place ; a number divisible by 10 , then this is a zero occurrence in the input ; move one decimal place ; 
def calculateAddedValue(number):
    result = 0
    decimalPlace = 1
    if (number == 0):
        result += (5 * decimalPlace)
    while (number > 0):
        if (number % 10 == 0):
            result += (5 * decimalPlace)
        number //= 10
        decimalPlace *= 10
    return result

def replace0with5(number):
    number += calculateAddedValue(number)
    return number


print(replace0with5(1020))

# Expected output:
1525
# program to find remainder without using modulo or % operator | this function returns remainder of num / divisor without using % ( modulo ) operator ; 
def getRemainder(num, divisor):
    return (num - divisor * (num // divisor))


num = 100
divisor = 7
print(getRemainder(num, divisor))

# Expected output:
2
# efficient program to compute sum of series 1 / 1 ! + 1 / 2 ! + 1 / 3 ! + 1 / 4 ! + . . + 1 / n ! | function to return value of 1 / 1 ! + 1 / 2 ! + . . + 1 / n ! ; update factorial ; update series sum ; 
def sum(n):
    sum = 0
    fact = 1
    for i in range(1, n + 1):
        fact *= i
        sum += 1.0 / fact
    print(sum)


n = 5
sum(n)

# Expected output:
1.7166666666666668
# print first k digits of 1 / n where n is a positive integer | python code to print first k digits of 1 / n where n is a positive integer ; function to print first k digits after dot in value of 1 / n . n is assumed to be a positive integer . ; initialize remainder ; run a loop k times to print k digits ; the next digit can always be obtained as doing ( 10 * rem ) / 10 ; update remainder ; 

import math


def Print(n, k):
    rem = 1
    for i in range(0, k):
        print(math .floor(((10 * rem) / n)), end="")
        rem = (10 * rem) % n


n = 7
k = 3
Print(n, k)
print(" ")
n = 21
k = 4
Print(n, k)

# Expected output:
142 
0476
# program to find sum of series 1 + 1 / 2 + 1 / 3 + 1 / 4 + . . + 1 / n | function to return sum of 1 / 1 + 1 / 2 + 1 / 3 + . . + 1 / n ; 
def sum(n):
    i = 1
    s = 0.0
    for i in range(1, n + 1):
        s = s + 1 / i
    return s


n = 5
print("Sum is", round(sum(n), 6))

# Expected output:
Sum is 2.283333
# program to find gcd or hcf of two numbers | recursive function to return gcd of a and b ; 
def gcd(a, b):
    if (b == 0):
        return a
    return gcd(b, a % b)


a = 98
b = 56
if (gcd(a, b)):
    print('GCD of', a, 'and', b, 'is', gcd(a, b))
else:
    print('not found')

# Expected output:
GCD of 98 and 56 is 14
# print all sequences of given length | a utility function that prints a given arr [ ] of length size ; the core function that recursively generates and prints all sequences of length k ; a function that uses printsequencesrecur ( ) to prints all sequences from 1 , 1 , . .1 to n , n , . . n ; 
def printArray(arr, size):
    for i in range(size):
        print(arr[i], end=" ")
    print("")
    return


def printSequencesRecur(arr, n, k, index):
    if (k == 0):
        printArray(arr, index)
    if (k > 0):
        for i in range(1, n + 1):
            arr[index] = i
            printSequencesRecur(arr, n, k - 1, index + 1)


def printSequences(n, k):
    arr = [0] * n
    printSequencesRecur(arr, n, k, 0)
    return


n = 3
k = 2
printSequences(n, k)

# Expected output:
1 1 
1 2 
1 3 
2 1 
2 2 
2 3 
3 1 
3 2 
3 3
# check if a number is multiple of 5 without using / and % operators | assumes that n is a positive integer ; 
def isMultipleof5(n):
    while (n > 0):
        n = n - 5
    if (n == 0):
        return 1
    return 0


i = 19
if (isMultipleof5(i) == 1):
    print(i, "is multiple of 5")
else:
    print(i, "is not a multiple of 5")

# Expected output:
19 is not a multiple of 5
# count pairs from an array having sum of twice of their and and xor equal to k | python3 program for the above approach ; function to count number of pairs satisfying the given conditions ; stores the frequency of array elements ; stores the total number of pairs ; traverse the array ; add it to cnt ; update frequency of current array element ; print the count ; given array ; size of the array ; 

from collections import defaultdict


def countPairs(arr, N, K):
    mp = defaultdict(int)
    cnt = 0
    for i in range(N):
        cnt += mp[K - arr[i]]
        mp[arr[i]] += 1
    print(cnt)


arr = [1, 5, 4, 8, 7]
N = len(arr)
K = 9
countPairs(arr, N, K)

# Expected output:
2
# bitwise operations on subarrays of size k | function to convert bit array to decimal number ; function to find minimum values of each bitwise and operation on element of subarray of size k ; maintain an integer array bit of size 32 all initialized to 0 ; create a sliding window of size k ; function call ; perform operation to removed element ; perform operation to add element ; taking minimum value ; return the result ; 
def build_num(bit, k):
    ans = 0
    for i in range(32):
        if (bit[i] == k):
            ans += (1 << i)
    return ans


def minimumAND(arr, n, k):
    bit = [0] * 32
    for i in range(k):
        for j in range(32):
            if ((arr[i] & (1 << j)) > 0):
                bit[j] += 1
    min_and = build_num(bit, k)
    for i in range(k, n):
        for j in range(32):
            if ((arr[i - k] & (1 << j)) > 0):
                bit[j] -= 1
        for j in range(32):
            if ((arr[i] & (1 << j)) > 0):
                bit[j] += 1
        min_and = min(build_num(bit, k), min_and)
    return min_and


if __name__ == '__main__':
    arr = [2, 5, 3, 6, 11, 13]
    k = 3
    n = len(arr)
    print(minimumAND(arr, n, k))

# Expected output:
0
# count pairs of elements such that number of set bits in their and is b [ i ] | function to return the count of pairs which satisfy the given condition ; check if the count of set bits in the and value is b [ j ] ; 
def solve(A, B, n):
    cnt = 0
    for i in range(n):
        for j in range(i, n):
            c = A[i] & A[j]
            if (bin(c).count('1') == B[j]):
                cnt += 1
    return cnt


if __name__ == "__main__":
    A = [2, 3, 1, 4, 5]
    B = [2, 2, 1, 4, 2]
    size = len(A)
    print(solve(A, B, size))

# Expected output:
4
# total pairs in an array such that the bitwise and , bitwise or and bitwise xor of lsb is 1 | function to find the count of required pairs ; to store the count of elements which give remainder 0 i . e . even values ; to store the count of elements which give remainder 1 i . e . odd values ; 
def CalculatePairs(a, n):
    cnt_zero = 0
    cnt_one = 0
    for i in range(0, n):
        if (a[i] % 2 == 0):
            cnt_zero += 1
        else:
            cnt_one += 1
    total_XOR_pairs = cnt_zero * cnt_one
    total_AND_pairs = (cnt_one) * (cnt_one - 1) / 2
    total_OR_pairs = cnt_zero * cnt_one + (cnt_one) * (cnt_one - 1) / 2
    print("cntXOR = ", int(total_XOR_pairs))
    print("cntAND = ", int(total_AND_pairs))
    print("cntOR = ", int(total_OR_pairs))


if __name__ == '__main__':
    a = [1, 3, 4, 2]
    n = len(a)
    CalculatePairs(a, n)

# Expected output:
cntXOR =  4
cntAND =  1
cntOR =  5
# assign other value to a variable from two possible values | function to alternate the values ; 
def alternate(a, b, x):
    x = a + b - x
    print("After change x is:", x)


if __name__ == '__main__':
    a = -10
    b = 15
    x = a
    print("x is:", x)
    alternate(a, b, x)

# Expected output:
x is: -10
After change x is: 15
# highest power of two that divides a given number | python3 program to find highest power of 2 that divides n . ; 
def highestPowerOf2(n):
    return (n & (~(n - 1)))


if __name__ == '__main__':
    n = 48
    print(highestPowerOf2(n))

# Expected output:
16
# check whether bitwise and of a number with any subset of an array is zero or not | function to check whether bitwise and of a number with any subset of an array is zero or not ; variable to store the and of all the elements ; find the and of all the elements of the array ; if the and of all the array elements and n is equal to zero ; 
def isSubsetAndZero(array, length, N):
    arrAnd = array[0]
    for i in range(1, length):
        arrAnd = arrAnd & array[i]
    if ((arrAnd & N) == 0):
        print("YES")
    else:
        print("NO")


if __name__ == "__main__":
    array = [1, 2, 4]
    length = len(array)
    N = 3
    isSubsetAndZero(array, length, N)

# Expected output:
YES
# finding the parity of a number efficiently | function to find the parity ; rightmost bit of y holds the parity value if ( y & 1 ) is 1 then parity is odd else even ; 
def findParity(x):
    y = x ^ (x >> 1)
    y = y ^ (y >> 2)
    y = y ^ (y >> 4)
    y = y ^ (y >> 8)
    y = y ^ (y >> 16)
    if (y & 1):
        return 1
    return 0


if (findParity(9) == 0):
    print("Even Parity")
else:
    print("OddParity")
if (findParity(13) == 0):
    print("Even Parity")
else:
    print("Odd Parity")

# Expected output:
Even Parity
Odd Parity
# check if bits in range l to r of two numbers are complement of each other or not | function to check whether all the bits are set in the given range or not ; calculating a number ' num ' having ' r ' number of bits and bits in the range l to r are the only set bits ; new number which will only have one or more set bits in the range l to r and nowhere else ; if both are equal , then all bits are set in the given range ; else all bits are not set ; function to check whether all the bits in the given range of two numbers are complement of each other ; 
def allBitsSetInTheGivenRange(n, l, r):
    num = ((1 << r) - 1) ^ ((1 << (l - 1)) - 1)
    new_num = n & num
    if (num == new_num):
        return True
    return False


def bitsAreComplement(a, b, l, r):
    xor_value = a ^ b
    return allBitsSetInTheGivenRange(xor_value, l, r)


if __name__ == "__main__":
    a = 10
    b = 5
    l = 1
    r = 3
    if (bitsAreComplement(a, b, l, r)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# sum of the series 2 ^ 0 + 2 ^ 1 + 2 ^ 2 + ... . . + 2 ^ n | function to calculate sum of series ; initialize sum to 0 ; loop to calculate sum of series ; calculate 2 ^ i ; 
def calculateSum(n):
    sum = 0
    for i in range(0, n):
        sum = sum + (1 << i)
    return sum


n = 10
print("Sum of series ", calculateSum(n))

# Expected output:
Sum of series  1023
# print all the combinations of n elements by changing sign such that their sum is divisible by m | function to print all the combinations ; iterate for all combinations ; initially 100 in binary if n is 3 as 1 << ( 3 - 1 ) = 100 in binary ; iterate in the array and assign signs to the array elements ; if the j - th bit from left is set take ' + ' sign ; right shift to check if jth bit is set or not ; re - initialize ; iterate in the array elements ; if the jth from left is set ; right shift ; 
def printCombinations(a, n, m):
    for i in range(0, (1 << n)):
        sum = 0
        num = 1 << (n - 1)
        for j in range(0, n):
            if ((i & num) > 0):
                sum += a[j]
            else:
                sum += (-1 * a[j])
            num = num >> 1
        if (sum % m == 0):
            num = 1 << (n - 1)
            for j in range(0, n):
                if ((i & num) > 0):
                    print("+", a[j], end=" ", sep="")
                else:
                    print("-", a[j], end=" ", sep="")
                num = num >> 1
            print("")


a = [3, 5, 6, 8]
n = len(a)
m = 5
printCombinations(a, n, m)

# Expected output:
-3 -5 +6 -8 
-3 +5 +6 -8 
+3 -5 -6 +8 
+3 +5 -6 +8
# same number of set bits as n |  ; function ; __builtin_popcount function that count set bits in n ; iterate from n - 1 to 1 ; check if the number of set bits equals to temp increment count ; 
def __builtin_popcount(n):
    t = 0
    while (n > 0):
        d = n % 2
        n = int(n / 2)
        if (d == 1):
            t = t + 1
    return t


def smallerNumsWithSameSetBits(n):
    temp = __builtin_popcount(n)
    count = 0
    for i in range(n - 1, 0, -1):
        if (temp == __builtin_popcount(i)):
            count = count + 1
    return count


n = 4
print(smallerNumsWithSameSetBits(n))

# Expected output:
2
# Multiply any Number with 4 using Bitwise Operator | function the return multiply a number with 4 using bitwise operator ; returning a number with multiply with 4 using2 bit shifring right ; derive function
def multiplyWith4(n):
    return (n << 2)


n = 4
print(multiplyWith4(n))

# Expected output:
16
# set all even bits of a number | sets even bits of n and returns modified number . ; generate 101010. . .10 number and store in res . ; if bit is even then generate number and or with res ; return or number ; 
def evenbitsetnumber(n):
    count = 0
    res = 0
    temp = n
    while (temp > 0):
        if (count % 2 == 1):
            res |= (1 << count)
        count += 1
        temp >>= 1
    return (n | res)


n = 10
print(evenbitsetnumber(n))

# Expected output:
10
# Set all even bits of a number | return msb set number ; set all bits ; return msb increment n by 1 and shift by 1 ; return even seted number ; get msb here ; generate even bits like 101010. . ; if bits is odd then shift by 1 ; return even set bits number ; set all even bits here ; take or with even set bits number ;
def getmsb(n):
    n |= n >> 1
    n |= n >> 2
    n |= n >> 4
    n |= n >> 8
    n |= n >> 16
    return (n + 1) >> 1


def getevenbits(n):
    n = getmsb(n)
    n |= n >> 2
    n |= n >> 4
    n |= n >> 8
    n |= n >> 16
    if (n & 1):
        n = n >> 1
    return n


def setallevenbits(n):
    return n | getevenbits(n)


n = 10
print(setallevenbits(n))

# Expected output:
10
# set all odd bits of a number | set all odd bit ; res for store 010101. . number ; generate number form of 010101. . ... till temp size ; if bit is odd , then generate number and or with res ; 
def oddbitsetnumber(n):
    count = 0
    res = 0
    temp = n
    while temp > 0:
        if count % 2 == 0:
            res |= (1 << count)
        count += 1
        temp >>= 1
    return (n | res)


n = 10
print(oddbitsetnumber(n))

# Expected output:
15
# set all odd bits of a number | efficient python3 program to set all odd bits number ; return msb set number ; set all bits including msb . ; return msb ; returns a number of same size ( msb at same position ) as n and all odd bits set . ; generate odd bits like 010101. . ; if bits is even then shift by 1 ; return odd set bits number ; set all odd bits here ; take or with odd set bits number ; 

import math


def getmsb(n):
    n |= n >> 1
    n |= n >> 2
    n |= n >> 4
    n |= n >> 8
    n |= n >> 16
    return (n + 1) >> 1


def getevenbits(n):
    n = getmsb(n)
    n |= n >> 2
    n |= n >> 4
    n |= n >> 8
    n |= n >> 16
    if ((n & 1) == 0):
        n = n >> 1
    return n


def setalloddbits(n):
    return n | getevenbits(n)


n = 10
print(setalloddbits(n))

# Expected output:
15
# print numbers in the range 1 to n having bits in alternate pattern | function to print numbers in the range 1 to nhaving bits in alternate pattern ; first number having bits in alternate pattern ; display ; loop until n < curr_num ; generate next number having alternate bit pattern ; if true then break ; display ; generate next number having alternate bit pattern ; if true then break ; display ; 
def printNumHavingAltBitPatrn(n):
    curr_num = 1
    print(curr_num)
    while (1):
        curr_num = curr_num << 1
        if (n < curr_num):
            break
        print(curr_num)
        curr_num = ((curr_num) << 1) ^ 1
        if (n < curr_num):
            break
        print(curr_num)


n = 50
printNumHavingAltBitPatrn(n)

# Expected output:
1
2
5
10
21
42
# smallest perfect power of 2 greater than n ( without using arithmetic operators ) | function to find smallest perfect power of 2 greater than n ; to store perfect power of 2 ; bitwise left shift by 1 ; bitwise right shift by 1 ; required perfect power of 2 ; 
def perfectPowerOf2(n):
    per_pow = 1
    while n > 0:
        per_pow = per_pow << 1
        n = n >> 1
    return per_pow


n = 128
print("Perfect power of 2 greater than", n, ":", perfectPowerOf2(n))

# Expected output:
Perfect power of 2 greater than 128 : 256
# find unique pair in an array with pairs of numbers | python 3 program to find a unique pair in an array of pairs . ; xor each element and get xor of two unique elements ( ans ) ; get a set bit of xor ( we get the rightmost set bit ) ; now divide elements in two sets by comparing rightmost set bit of xor with bit at same position in each element . ; xor of first set in arr [ ] ; xor of second set in arr [ ] ; 
def findUniquePair(arr, n):
    XOR = arr[0]
    for i in range(1, n):
        XOR = XOR ^ arr[i]
    set_bit_no = XOR & ~(XOR - 1)
    x = 0
    y = 0
    for i in range(0, n):
        if (arr[i] & set_bit_no):
            x = x ^ arr[i]
        else:
            y = y ^ arr[i]
    print("The unique pair is (", x, ", ", y, ")", sep="")


a = [6, 1, 3, 5, 1, 3, 7, 6]
n = len(a)
findUniquePair(a, n)

# Expected output:
The unique pair is (7, 5)