giulio98/xlcost-single-prompt huggingface dataset:
# n queen problem | backtracking | python3 program to solve n queen problem using backtracking ; ld is an array where its indices indicate row - col + n - 1 ( n - 1 ) is for shifting the difference to store negative indices ; rd is an array where its indices indicate row + col and used to check whether a queen can be placed on right diagonal or not ; column array where its indices indicates column and used to check whether a queen can be placed in that row or not ; a utility function to print solution ; a recursive utility function to solve n queen problem ; base case : if all queens are placed then return true ; consider this column and try placing this queen in all rows one by one ; a check if a queen can be placed on board [ row ] [ col ] . we just need to check ld [ row - col + n - 1 ] and rd [ row + coln ] where ld and rd are for left and right diagonal respectively ; place this queen in board [ i ] [ col ] ; recur to place rest of the queens ; board [ i ] [ col ] = 0 backtrack ; if the queen cannot be placed in any row in this colum col then return false ; this function solves the n queen problem using backtracking . it mainly uses solvenqutil ( ) to solve the problem . it returns false if queens cannot be placed , otherwise , return true and prints placement of queens in the form of 1 s . please note that there may be more than one solutions , this function prints one of the feasible solutions . ; 

N = 4
ld = [0] * 30
rd = [0] * 30
cl = [0] * 30


def printSolution(board):
    for i in range(N):
        for j in range(N):
            print(board[i][j], end=" ")
        print()


def solveNQUtil(board, col):
    if (col >= N):
        return True
    for i in range(N):
        if ((ld[i - col + N - 1] != 1 and rd[i + col] != 1) and cl[i] != 1):
            board[i][col] = 1
            ld[i - col + N - 1] = rd[i + col] = cl[i] = 1
            if (solveNQUtil(board, col + 1)):
                return True
            ld[i - col + N - 1] = rd[i + col] = cl[i] = 0
    return False


def solveNQ():
    board = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
    if (solveNQUtil(board, 0) == False):
        printf("Solution does not exist")
        return False
    printSolution(board)
    return True


solveNQ()

# Expected output:
1 0 1 0 
1 0 1 0 
0 1 0 1 
0 1 0 0
# given an array a [ ] and a number x , check for pair in a [ ] with sum as x | function to print pairs ; initializing the rem values with 0 's. ; perform the remainder operation only if the element is x , as numbers greater than x can 't  be used to get a sum x.updating  the count of remainders. ; traversing the remainder list from start to middle to find pairs ; the elements with remainders i and x - i will result to a sum of x . once we get two elements which add up to x , we print x and break . ; once we reach middle of remainder array , we have to do operations based on x . ; if x is even and we have more than 1 elements with remainder x / 2 , then we will have two distinct elements which add up to x . if we dont have than 1 element , print " no " . ; when x is odd we continue the same process which we did in previous loop . ; 
def printPairs(a, n, x):
    rem = []
    for i in range(x):
        rem .append(0)
    for i in range(n):
        if (a[i] < x):
            rem[a[i] % x] += 1
    for i in range(1, x // 2):
        if (rem[i] > 0 and rem[x - i] > 0):
            print("Yes")
            break
    if (i >= x // 2):
        if (x % 2 == 0):
            if (rem[x // 2] > 1):
                print("Yes")
            else:
                print("No")
        else:
            if (rem[x // 2] > 0 and rem[x - x // 2] > 0):
                print("Yes")
            else:
                print("No")


A = [1, 4, 45, 6, 10, 8]
n = 16
arr_size = len(A)
printPairs(A, arr_size, n)

# Expected output:
Yes
# find remainder when a number a raised to n factorial is divided by p | function to calculate factorial of a number ; calculating factorial ; returning factorial ; function to calculate resultant remainder ; function call to calculate factorial of n ; calculating remainder ; returning resultant remainder ; 
def fact(n):
    ans = 1
    for i in range(2, n + 1, 1):
        ans *= i
    return ans


def remainder(n, a, p):
    len1 = fact(n)
    ans = 1
    for i in range(1, len1 + 1, 1):
        ans = (ans * a) % p
    return ans


if __name__ == '__main__':
    A = 2
    N = 1
    P = 2
    print(remainder(N, A, P))

# Expected output:
0
# check if a number n can be expressed in base b | function to check if a number n can be expressed in base b ; check if n is greater than 0 ; initialize a boolean variable ; check if digit is 0 or 1 ; subtract the appropriate power of b from it and increment higher digit ; 
def check(n, w):
    a = [0 for i in range(105)]
    p = 0
    while (n > 0):
        a[p] = n % w
        p += 1
        n //= w
    flag = True
    for i in range(101):
        if (a[i] == 0 or a[i] == 1):
            continue
        elif (a[i] == w or a[i] == w - 1):
            a[i + 1] += 1
        else:
            flag = False
    return flag


if __name__ == "__main__":
    B = 3
    N = 7
    if (check(N, B)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# count of groups among n people having only one leader in each group | python3 program for the above approach ; function to find 2 ^ x using modular exponentiation ; base cases ; if b is even ; if b is odd ; function to count the number of ways to form the group having one leader ; find 2 ^ ( n - 1 ) using modular exponentiation ; count total ways ; print the total ways ; 

mod = 1000000007


def exponentMod(A, B):
    if (A == 0):
        return 0
    if (B == 0):
        return 1
    y = 0
    if (B % 2 == 0):
        y = exponentMod(A, B // 2)
        y = (y * y) % mod
    else:
        y = A % mod
        y = (y * exponentMod(A, B - 1) % mod) % mod
    return ((y + mod) % mod)


def countWays(N):
    select = exponentMod(2, N - 1)
    ways = ((N % mod) * (select % mod))
    ways %= mod
    print(ways)


if __name__ == '__main__':
    N = 5
    countWays(N)

# Expected output:
80
# expected number of moves to reach the end of a board | matrix exponentiation | python3 implementation of the approach ; function to multiply two 7 * 7 matrix ; function to perform matrix exponentiation ; 7 * 7 identity matrix ; loop to find the power ; function to return the required count ; base cases ; multiplier matrix ; finding the required multiplier i . e mul ^ ( x - 6 ) ; final answer ; 

import numpy as np
maxSize = 50


def matrix_product(a, b):
    c = np .zeros((7, 7))
    for i in range(7):
        for j in range(7):
            for k in range(7):
                c[i][j] += a[i][k] * b[k][j]
    return c


def mul_expo(mul, p):
    s = [
        [
            1, 0, 0, 0, 0, 0, 0], [
            0, 1, 0, 0, 0, 0, 0], [
                0, 0, 1, 0, 0, 0, 0], [
                    0, 0, 0, 1, 0, 0, 0], [
                        0, 0, 0, 0, 1, 0, 0], [
                            0, 0, 0, 0, 0, 1, 0], [
                                0, 0, 0, 0, 0, 0, 1]]
    while (p != 1):
        if (p % 2 == 1):
            s = matrix_product(s, mul)
        mul = matrix_product(mul, mul)
        p //= 2
    return matrix_product(mul, s)


def expectedSteps(x):
    if (x == 0):
        return 0
    if (x <= 6):
        return 6
    mul = [[7 / 6, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0,
                                                                                     0, 1, 0, 0], [0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 1], [-1 / 6, 0, 0, 0, 0, 0, 0]]
    mul = mul_expo(mul, x - 6)
    return (mul[0][0] + mul[1][0] + mul[2][0] +
            mul[3][0] + mul[4][0] + mul[5][0]) * 6


if __name__ == "__main__":
    n = 10
    print(expectedSteps(n - 1))

# Expected output:
7.361111111111114
# place the prisoners into cells to maximize the minimum difference between any two | function that returns true if the prisoners can be placed such that the minimum distance between any two prisoners is at least sep ; considering the first prisoner is placed at 1 st cell ; if the first prisoner is placed at the first cell then the last_prisoner_placed will be the first prisoner placed and that will be in cell [ 0 ] ; checking if the prisoner can be placed at ith cell or not ; if all the prisoners got placed then return true ; function to return the maximized distance ; sort the array so that binary search can be applied on it ; minimum possible distance for the search space ; maximum possible distance for the search space ; to store the result ; binary search ; if the prisoners can be placed such that the minimum distance between any two prisoners is at least mid ; update the answer ; 
def canPlace(a, n, p, sep):
    prisoners_placed = 1
    last_prisoner_placed = a[0]
    for i in range(1, n):
        current_cell = a[i]
        if (current_cell - last_prisoner_placed >= sep):
            prisoners_placed += 1
            last_prisoner_placed = current_cell
            if (prisoners_placed == p):
                return True
    return False


def maxDistance(cell, n, p):
    cell = sorted(cell)
    start = 0
    end = cell[n - 1] - cell[0]
    ans = 0
    while (start <= end):
        mid = start + ((end - start) // 2)
        if (canPlace(cell, n, p, mid)):
            ans = mid
            start = mid + 1
        else:
            end = mid - 1
    return ans


cell = [1, 2, 8, 4, 9]
n = len(cell)
p = 3
print(maxDistance(cell, n, p))

# Expected output:
3
# find n in the given matrix that follows a pattern | function to return the row and the column of the given integer ; binary search for the row number ; condition to get the maximum x that satisfies the criteria ; binary search for the column number ; condition to get the maximum y that satisfies the criteria ; get the row and the column number ; return the pair ; 
def solve(n):
    low = 1
    high = 10 ** 4
    x, p = n, 0
    while (low <= high):
        mid = (low + high) // 2
        sum = (mid * (mid + 1)) // 2
        if (x - sum >= 1):
            p = mid
            low = mid + 1
        else:
            high = mid - 1
    start, end, y, q = 1, 10 ** 4, 1, 0
    while (start <= end):
        mid = (start + end) // 2
        sum = (mid * (mid + 1)) // 2
        if (y + sum <= n):
            q = mid
            start = mid + 1
        else:
            end = mid - 1
    x = x - (p * (p + 1)) // 2
    y = y + (q * (q + 1)) // 2
    r = x
    c = q + 1 - n + y
    return r, c


n = 5
r, c = solve(n)
print(r, c)

# Expected output:
2 2
# smallest subarray with gcd as 1 | segment tree | python3 implementation of the approach ; array to store segment - tree ; function to build segment - tree to answer range gcd queries ; base - case ; mid element of the range ; merging the result of left and right sub - tree ; function to perform range gcd queries ; base - cases ; mid - element ; calling left and right child ; function to find the required length ; buildinng the segment tree ; two pointer variables ; to store the final answer ; loopinng ; incrementing j till we don 't get a gcd value of 1 ; updating the final answer ; incrementing i ; updating j ; returning the final answer ; 

from math import gcd as __gcd
maxLen = 30
seg = [0 for i in range(3 * maxLen)]


def build(l, r, inn, arr):
    if (l == r):
        seg[inn] = arr[l]
        return seg[inn]
    mid = (l + r) // 2
    seg[inn] = __gcd(
        build(
            l,
            mid,
            2 * inn + 1,
            arr),
        build(
            mid + 1,
            r,
            2 * inn + 2,
            arr))
    return seg[inn]


def query(l, r, l1, r1, inn):
    if (l1 <= l and r <= r1):
        return seg[inn]
    if (l > r1 or r < l1):
        return 0
    mid = (l + r) // 2
    x = __gcd(
        query(
            l,
            mid,
            l1,
            r1,
            2 * inn + 1),
        query(
            mid + 1,
            r,
            l1,
            r1,
            2 * inn + 2))
    return x


def findLen(arr, n):
    build(0, n - 1, 0, arr)
    i = 0
    j = 0
    ans = 10 ** 9
    while (i < n):
        while (j < n and query(0, n - 1, i, j, 0) != 1):
            j += 1
        if (j == n):
            break
        ans = minn((j - i + 1), ans)
        i += 1
        j = max(j, i)
    if (ans == 10 ** 9):
        return -1
    else:
        return ans


arr = [2, 2, 2]
n = len(arr)
print(findLen(arr, n))

# Expected output:
-1
# find an n x n grid whose xor of every row and column is equal | function to find the n x n matrix that satisfies the given condition ; initialize x to 0 ; divide the n x n matrix into n / 4 matrices for each of the n / 4 rows where each matrix is of size 4 x 4 ; print the generated matrix ; 
def findGrid(n):
    arr = [[0 for k in range(n)]for l in range(n)]
    x = 0
    for i in range(n // 4):
        for j in range(n // 4):
            for k in range(4):
                for l in range(4):
                    arr[i * 4 + k][j * 4 + l] = x
                    x += 1
    for i in range(n):
        for j in range(n):
            print(arr[i][j], end=" ")
        print()


n = 4
findGrid(n)

# Expected output:
0 1 2 3 
4 5 6 7 
8 9 10 11 
12 13 14 15
# kth smallest element in the array using constant space when array can 't be modified | function to return the kth smallest element from the array ; minimum and maximum element from the array ; modified binary search ; to store the count of elements from the array which are less than mid and the elements which are equal to mid ; if mid is the kth smallest ; if the required element is less than mid ; if the required element is greater than mid ; 
def kthSmallest(arr, k, n):
    low = min(arr)
    high = max(arr)
    while (low <= high):
        mid = low + (high - low) // 2
        countless = 0
        countequal = 0
        for i in range(n):
            if (arr[i] < mid):
                countless += 1
            elif (arr[i] == mid):
                countequal += 1
        if (countless < k and (countless + countequal) >= k):
            return mid
        elif (countless >= k):
            high = mid - 1
        elif (countless < k and countless + countequal < k):
            low = mid + 1


if __name__ == "__main__":
    arr = [7, 10, 4, 3, 20, 15]
    n = len(arr)
    k = 3
    print(kthSmallest(arr, k, n))

# Expected output:
7
# find 2 ^ ( 2 ^ a ) % b | function to return 2 ^ ( 2 ^ a ) % b ; base case , 2 ^ ( 2 ^ 1 ) % b = 4 % b ; 
def F(A, B):
    if (A == 1):
        return (4 % B)
    else:
        temp = F(A - 1, B)
        return (temp * temp) % B


A = 25
B = 50
print(F(A, B))

# Expected output:
46
# sum of i * countdigits ( i ) ^ 2 for all i in range [ l , r ] | python3 implementation of the approach ; function to return the required sum ; if range is valid ; sum of ap ; 

MOD = 1000000007


def rangeSum(l, r):
    a = 1
    b = 9
    res = 0
    for i in range(1, 11):
        L = max(l, a)
        R = min(r, b)
        if (L <= R):
            sum = (L + R) * (R - L + 1) // 2
            res += (i * i) * (sum % MOD)
            res %= MOD
        a *= 10
        b = b * 10 + 9
    return res


if __name__ == "__main__":
    l = 98
    r = 102
    print(rangeSum(l, r))

# Expected output:
3515
# minimum number n such that total set bits of all numbers from 1 to n is at | python3 implementation of the above approach ; function to count sum of set bits of all numbers till n ; function to find the minimum number ; binary search for the lowest number ; find mid number ; check if it is atleast x ; 

INF = 99999
size = 10


def getSetBitsFromOneToN(N):
    two, ans = 2, 0
    n = N
    while (n > 0):
        ans += (N // two) * (two >> 1)
        if ((N & (two - 1)) > (two >> 1) - 1):
            ans += (N & (two - 1)) - (two >> 1) + 1
        two <<= 1
        n >>= 1
    return ans


def findMinimum(x):
    low = 0
    high = 100000
    ans = high
    while (low <= high):
        mid = (low + high) >> 1
        if (getSetBitsFromOneToN(mid) >= x):
            ans = min(ans, mid)
            high = mid - 1
        else:
            low = mid + 1
    return ans


x = 20
print(findMinimum(x))

# Expected output:
11
# range and update sum queries with factorial | python3 program to calculate sum of factorials in an interval and update with two types of operations ; modulus ; maximum size of input array ; size for factorial array ; structure for queries with members type , leftindex , rightindex of the query ; function for updating the value ; function for calculating the required sum between two indexes ; function to return answer to queries ; precomputing factorials ; declaring a set ; inserting indexes of those numbers which are lesser than 40 ; update query of the 1 st type ; find the left index of query in the set using binary search ; if it crosses the right index of query or end of set , then break ; update the value of arr [ i ] to its new value ; if updated value becomes greater than or equal to 40 remove it from the set ; increment the index ; update query of the 2 nd type ; update the value to its new value ; if the value is less than 40 , insert it into set , otherwise remove it ; sum query of the 3 rd type ; 

from bisect import bisect_left as lower_bound
MOD = 1e9
MAX = 100
SZ = 40
BIT = [0] * (MAX + 1)
fact = [0] * (SZ + 1)


class queries:
    def __init__(self, tpe, l, r):
        self .type = tpe
        self .l = l
        self .r = r


def update(x, val, n):
    global BIT
    while x <= n:
        BIT[x] += val
        x += x & -x


def summ(x):
    global BIT
    s = 0
    while x > 0:
        s += BIT[x]
        x -= x & -x
    return s


def answerQueries(arr: list, que: list, n: int, q: int):
    global fact
    fact[0] = 1
    for i in range(1, 41):
        fact[i] = int((fact[i - 1] * i) % MOD)
    s = set()
    for i in range(1, n):
        if arr[i] < 40:
            s .add(i)
            update(i, fact[arr[i]], n)
        else:
            update(i, 0, n)
    for i in range(q):
        if que[i].type == 1:
            while True:
                s = sorted(s)
                it = lower_bound(s, que[i].l)
                if it == len(s) or s[it] > que[i].r:
                    break
                que[i].l = s[it]
                val = arr[s[it]] + 1
                update(s[it], fact[val] - fact[arr[s[it]]], n)
                arr[s[it]] += 1
                if arr[s[it]] >= 40:
                    s .remove(it)
                que[i].l += 1
        elif que[i].type == 2:
            s = set(s)
            idx = que[i].l
            val = que[i].r
            update(idx, fact[val] - fact[arr[idx]], n)
            arr[idx] = val
            if val < 40:
                s .add(idx)
            else:
                s .remove(idx)
        else:
            print((summ(que[i].r) - summ(que[i].l - 1)))


if __name__ == "__main__":
    q = 6
    arr = [0, 1, 2, 1, 4, 5]
    n = len(arr)
    que = [
        queries(
            3, 1, 5), queries(
            1, 1, 3), queries(
                2, 2, 4), queries(
                    3, 2, 4), queries(
                        1, 2, 5), queries(
                            3, 1, 5)]
    answerQueries(arr, que, n, q)

# Expected output:
148
50
968
# numbers whose factorials end with n zeros | function to calculate trailing zeros ; binary search for first number with n trailing zeros ; print all numbers after low with n trailing zeros . ; print result ; 
def trailingZeroes(n):
    cnt = 0
    while n > 0:
        n = int(n / 5)
        cnt += n
    return cnt


def binarySearch(n):
    low = 0
    high = 1e6
    while low < high:
        mid = int((low + high) / 2)
        count = trailingZeroes(mid)
        if count < n:
            low = mid + 1
        else:
            high = mid
    result = list()
    while trailingZeroes(low) == n:
        result .append(low)
        low += 1
    for i in range(len(result)):
        print(result[i], end=" ")


n = 2
binarySearch(n)

# Expected output:
10 11 12 13 14
# number of days after which tank will become empty | utility method to get sum of first n numbers ; method returns minimum number of days after which tank will become empty ; if water filling is more than capacity then after c days only tank will become empty ; initialize binary search variable ; loop until low is less than high ; if cumulate sum is greater than ( c - l ) then search on left side ; if ( c - l ) is more then search on right side ; final answer will be obtained by adding l to binary search result ; 
def getCumulateSum(n):
    return int((n * (n + 1)) / 2)


def minDaysToEmpty(C, l):
    if (C <= l):
        return C
    lo, hi = 0, 1e4
    while (lo < hi):
        mid = int((lo + hi) / 2)
        if (getCumulateSum(mid) >= (C - l)):
            hi = mid
        else:
            lo = mid + 1
    return (l + lo)


C, l = 5, 2
print(minDaysToEmpty(C, l))

# Expected output:
4
# number of days after which tank will become empty | python3 code to find number of days after which tank will become empty ; method returns minimum number of days after which tank will become empty ; 

import math


def minDaysToEmpty(C, l):
    if (l >= C):
        return C
    eq_root = (math .sqrt(1 + 8 * (C - l)) - 1) / 2
    return math .ceil(eq_root) + l


print(minDaysToEmpty(5, 2))
print(minDaysToEmpty(6514683, 4965))

# Expected output:
4
8573
# k | program to find kth element from two sorted arrays ; 
def kth(arr1, arr2, m, n, k):
    sorted1 = [0] * (m + n)
    i = 0
    j = 0
    d = 0
    while (i < m and j < n):
        if (arr1[i] < arr2[j]):
            sorted1[d] = arr1[i]
            i += 1
        else:
            sorted1[d] = arr2[j]
            j += 1
        d += 1
    while (i < m):
        sorted1[d] = arr1[i]
        d += 1
        i += 1
    while (j < n):
        sorted1[d] = arr2[j]
        d += 1
        j += 1
    return sorted1[k - 1]


arr1 = [2, 3, 6, 7, 9]
arr2 = [1, 4, 8, 10]
k = 5
print(kth(arr1, arr2, 5, 4, k))

# Expected output:
6
# K | Python program to find k - th element from two sorted arrays
def kth(arr1, arr2, n, m, k):
    if n == 1 or m == 1:
        if m == 1:
            arr2, arr1 = arr1, arr2
            m = n
        if k == 1:
            return min(arr1[0], arr2[0])
        elif k == m + 1:
            return max(arr1[0], arr2[0])
        else:
            if arr2[k - 1] < arr1[0]:
                return arr2[k - 1]
            else:
                return max(arr1[0], arr2[k - 2])
    mid1 = (n - 1) // 2
    mid2 = (m - 1) // 2
    if mid1 + mid2 + 1 < k:
        if arr1[mid1] < arr2[mid2]:
            return kth(arr1[mid1 + 1:], arr2, n - mid1 - 1, m, k - mid1 - 1)
        else:
            return kth(arr1, arr2[mid2 + 1:], n, m - mid2 - 1, k - mid2 - 1)
    else:
        if arr1[mid1] < arr2[mid2]:
            return kth(arr1, arr2[:mid2 + 1], n, mid2 + 1, k)
        else:
            return kth(arr1[:mid1 + 1], arr2, mid1 + 1, m, k)


if __name__ == "__main__":
    arr1 = [2, 3, 6, 7, 9]
    arr2 = [1, 4, 8, 10]
    k = 5
    print(kth(arr1, arr2, 5, 4, k))

# Expected output:
6