giulio98/xlcost-single-prompt huggingface dataset:
# minimum operations required to modify the array such that parity of adjacent elements is different | function to return the parity of a number ; function to return the minimum number of operations required ; operation needs to be performed ; parity of previous element ; parity of next element ; update parity of current element to be other than the parities of the previous and the next number ; 
def parity(a):
    return a % 3


def solve(array, size):
    operations = 0
    for i in range(0, size - 1):
        if parity(array[i]) == parity(array[i + 1]):
            operations += 1
            if i + 2 < size:
                pari1 = parity(array[i])
                pari2 = parity(array[i + 2])
                if pari1 == pari2:
                    if pari1 == 0:
                        array[i + 1] = 1
                    elif pari1 == 1:
                        array[i + 1] = 0
                    else:
                        array[i + 1] = 1
                else:
                    if ((pari1 == 0 and pari2 == 1) or (
                            pari1 == 1 and pari2 == 0)):
                        array[i + 1] = 2
                    if ((pari1 == 1 and pari2 == 2) or (
                            pari1 == 2 and pari2 == 1)):
                        array[i + 1] = 0
                    if ((pari1 == 2 and pari2 == 0) and (
                            pari1 == 0 and pari2 == 2)):
                        array[i + 1] = 1
    return operations


if __name__ == "__main__":
    array = [2, 1, 3, 0]
    size = len(array)
    print(solve(array, size))

# Expected output:
1
# number of submatrices with or value 1 | function to find required prefix - count for each row from right to left ; function to find the count of submatrices with or value 1 ; array to store prefix count of zeros from right to left for boolean array ; variable to store the count of submatrices with or value 0 ; loop to evaluate each column of the prefix matrix uniquely . for each index of a column we will try to determine the number of sub - matrices starting from that index and has all 1 s ; first part of pair will be the value of inserted element . second part will be the count of the number of elements pushed before with a greater value ; variable to store the number of submatrices with all 0 s ; return the final answer ; 
def findPrefixCount(p_arr, arr):
    for i in range(0, n):
        for j in range(n - 1, -1, -1):
            if arr[i][j]:
                continue
            if j != n - 1:
                p_arr[i][j] += p_arr[i][j + 1]
            p_arr[i][j] += int(not arr[i][j])


def matrixOrValueOne(arr):
    p_arr = [[0 for i in range(n)]for j in range(n)]
    findPrefixCount(p_arr, arr)
    count_zero_submatrices = 0
    for j in range(0, n):
        i = n - 1
        q = []
        to_sum = 0
        while i >= 0:
            c = 0
            while (len(q) != 0 and q[-1][0] > p_arr[i][j]):
                to_sum -= ((q[-1][1] + 1) * (q[-1][0] - p_arr[i][j]))
                c += q .pop()[1] + 1
            to_sum += p_arr[i][j]
            count_zero_submatrices += to_sum
            q .append((p_arr[i][j], c))
            i -= 1
    return ((n * (n + 1) * n * (n + 1)) // 4 - count_zero_submatrices)


if __name__ == "__main__":
    n = 3
    arr = [[0, 0, 0], [0, 1, 0], [0, 0, 0]]
    print(matrixOrValueOne(arr))

# Expected output:
16
# xor of xors of all sub | function to find to required xor value ; nested loop to find the number of sub - matrix each index belongs to ; number of ways to choose from top - left elements ; number of ways to choose from bottom - right elements ; 
def submatrixXor(arr, n):
    ans = 0
    for i in range(0, n):
        for j in range(0, n):
            top_left = (i + 1) * (j + 1)
            bottom_right = (n - i) * (n - j)
            if (top_left % 2 == 1 and bottom_right % 2 == 1):
                ans = (ans ^ arr[i][j])
    return ans


n = 3
arr = [[6, 7, 13], [8, 3, 4], [9, 7, 6]]
print(submatrixXor(arr, n))

# Expected output:
4
# find nth positive number whose digital root is x | python3 program to find the n - th number whose digital root is x ; function to find the digital root of a number ; function to find the nth number with digital root as x ; counter variable to keep the count of valid numbers ; find digital root ; check if is required answer or not ; print the answer if you have found it and breakout of the loop ; 

import sys


def findDigitalRoot(num):
    sum = sys .maxsize
    tempNum = num
    while (sum >= 10):
        sum = 0
        while (tempNum > 0):
            sum += tempNum % 10
            tempNum //= 10
        tempNum = sum
    return sum


def findAnswer(X, N):
    counter = 0
    i = 0
    while (counter < N):
        i += 1
        digitalRoot = findDigitalRoot(i)
        if (digitalRoot == X):
            counter += 1
        if (counter == N):
            print(i)
            break


if __name__ == '__main__':
    X = 1
    N = 3
    findAnswer(X, N)

# Expected output:
19
# find nth positive number whose digital root is x | function to find the n - th number with digital root as x ; 
def findAnswer(X, N):
    return (N - 1) * 9 + X


X = 7
N = 43
print(findAnswer(X, N))

# Expected output:
385
# sum of the natural numbers ( up to n ) whose modulo with k yield r | function to return the sum ; if current number gives r as the remainder on dividing by k ; update the sum ; return the sum ; 
def count(N, K, R):
    sum = 0
    for i in range(1, N + 1):
        if (i % K == R):
            sum += i
    return sum


if __name__ == '__main__':
    N = 20
    K = 4
    R = 3
    print(count(N, K, R))

# Expected output:
55
# longest sub | function to return the length of the longest required sub - sequence ; find the maximum element from the array ; insert all lucas numbers below max to the set a and b are first two elements of the lucas sequence ; if current element is a lucas number , increment count ; return the count ; 
def LucasSequence(arr, n):
    max = arr[0]
    for i in range(len(arr)):
        if (arr[i] > max):
            max = arr[i]
    s = set()
    a = 2
    b = 1
    s .add(a)
    s .add(b)
    while (b < max):
        c = a + b
        a = b
        b = c
        s .add(b)
    count = 0
    for i in range(n):
        if (arr[i] in s):
            count += 1
    return count


if __name__ == '__main__':
    arr = [7, 11, 22, 4, 2, 1, 8, 9]
    n = len(arr)
    print(LucasSequence(arr, n))

# Expected output:
5
# find the number of solutions to the given equation | function to return the count of valid values of x ; iterate through all possible sum of digits of x ; get current value of x for sum of digits i ; find sum of digits of cr ; if cr is a valid choice for x ; return the count ; 
def getCount(a, b, c):
    count = 0
    for i in range(1, 82):
        cr = b * pow(i, a) + c
        tmp = cr
        sm = 0
        while (tmp):
            sm += tmp % 10
            tmp //= 10
        if (sm == i and cr < 10 ** 9):
            count += 1
    return count


a, b, c = 3, 2, 8
print(getCount(a, b, c))

# Expected output:
3
# check if an array of 1 s and 2 s can be divided into 2 parts with equal sum | function to check if it is possible to split the array in two halfs with equal sum ; calculate sum of elements and count of 1 's ; if total sum is odd , return false ; if sum of each half is even , return true ; if sum of each half is even but there is atleast one 1 ; 
def isSpiltPossible(n, a):
    Sum = 0
    c1 = 0
    for i in range(n):
        Sum += a[i]
        if (a[i] == 1):
            c1 += 1
    if (Sum % 2):
        return False
    if ((Sum // 2) % 2 == 0):
        return True
    if (c1 > 0):
        return True
    else:
        return False


n = 3
a = [1, 1, 2]
if (isSpiltPossible(n, a)):
    print("YES")
else:
    print("NO")

# Expected output:
YES
# make a tree with n vertices , d diameter and at most vertex degree k | function to make a tree with n vertices , d as it 's diameter and degree of each vertex is at most k ; if diameter > n - 1 impossible to build tree ; to store the degree of each vertex ; to store the edge between vertices ; to store maximum distance among all the paths from a vertex ; make diameter of tree equals to d ; add an edge between them ; store maximum distance of each vertex from other vertices ; for next ( n - d - 1 ) edges ; if the vertex already has the degree k ; if not possible ; increase the degree of vertices ; add an edge between them ; store the maximum distance of this vertex from other vertices ; prall the edges of the built tree ; 
def Make_tree(n, d, k):
    if (d > n - 1):
        print("No")
        return
    deg = [0] * (n)
    ans = []
    q = {}
    for i in range(d):
        deg[i] += 1
        deg[i + 1] += 1
        if (deg[i] > k or deg[i + 1] > k):
            print("NO")
            return
        ans .append((i, i + 1))
    for i in range(1, d):
        q[(max(i, d - i), i)] = 1
    for i in range(d + 1, n):
        arr = list(q .keys())
        while (len(q) > 0 and deg[arr[0][1]] == k):
            del q[arr[0]]
        if (len(q) == 0 or arr[0][0] == d):
            print("No")
            return
        deg[i] += 1
        deg[arr[0][1]] += 1
        ans .append((i, arr[0][1]))
        q[(arr[0][0] + 1, i)] = 1
    for i in range(n - 1):
        print(ans[i][0] + 1, ans[i][1] + 1)


if __name__ == '__main__':
    n, d, k = 6, 3, 4
    Make_tree(n, d, k)

# Expected output:
1 2
2 3
3 4
5 2
6 2
# sum of all submatrices of a given matrix | python3 program to find the sum of all possible submatrices of a given matrix ; function to find the sum of all possible submatrices of a given matrix ; variable to store the required sum ; nested loop to find the number of submatrices , each number belongs to ; number of ways to choose from top - left elements ; number of ways to choose from bottom - right elements ; 

n = 3


def matrixSum(arr):
    sum = 0
    for i in range(n):
        for j in range(n):
            top_left = (i + 1) * (j + 1)
            bottom_right = (n - i) * (n - j)
            sum += (top_left * bottom_right * arr[i][j])
    return sum


if __name__ == "__main__":
    arr = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
    print(matrixSum(arr))

# Expected output:
100
# maximum bitwise and pair from given range | function to return the maximum bitwise and possible among all the possible pairs ; maximum among all ( i , j ) pairs ; 
def maxAND(L, R):
    maximum = L & R
    for i in range(L, R, 1):
        for j in range(i + 1, R + 1, 1):
            maximum = max(maximum, (i & j))
    return maximum


if __name__ == '__main__':
    L = 1
    R = 632
    print(maxAND(L, R))

# Expected output:
630
# split the array into odd number of segments of odd lengths | function to check ; check the result by processing the first & last element and size ; 
def checkArray(arr, n):
    return ((arr[0] % 2) and (arr[n - 1] % 2) and (n % 2))


arr = [1, 2, 3, 4, 5]
n = len(arr)
if checkArray(arr, n):
    print(1)
else:
    print(0)

# Expected output:
1
# minimum removals to make array sum odd | function to find minimum removals ; count odd numbers ; if the counter is odd return 0 otherwise return 1 ; 
def findCount(arr, n):
    countOdd = 0
    for i in range(n):
        if (arr[i] % 2 == 1):
            countOdd += 1
    if (countOdd % 2 == 0):
        return 1
    else:
        return 0


if __name__ == "__main__":
    arr = [1, 2, 3, 5, 1]
    n = len(arr)
    print(findCount(arr, n))

# Expected output:
1
# check whether the number can be made perfect square after adding 1 | python3 implementation of the approach ; function that returns true if x is a perfect square ; find floating po value of square root of x ; if square root is an eger ; function that returns true if n is a sunny number ; if ( n + 1 ) is a perfect square ; 

import math as mt


def isPerfectSquare(x):
    sr = mt .sqrt(x)
    return ((sr - mt .floor(sr)) == 0)


def isSunnyNum(n):
    if (isPerfectSquare(n + 1)):
        return True
    return False


n = 3
if (isSunnyNum(n)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# minimum operations to make counts of remainders same in an array | function to return the minimum number of operations required ; to store modulos values ; if it 's size greater than k  it needed to be decreased ; if it 's size is less than k  it needed to be increased ; 
def minOperations(n, a, m):
    k = n // m
    val = [[]for i in range(m)]
    for i in range(0, n):
        val[a[i] % m].append(i)
    ans = 0
    extra = []
    for i in range(0, 2 * m):
        cur = i % m
        while len(val[cur]) > k:
            elem = val[cur].pop()
            extra .append((elem, i))
        while (len(val[cur]) < k and len(extra) > 0):
            elem = extra[-1][0]
            mmod = extra[-1][1]
            extra .pop()
            val[cur].append(elem)
            ans += i - mmod
    return ans


if __name__ == "__main__":
    m = 3
    a = [3, 2, 0, 6, 10, 12]
    n = len(a)
    print(minOperations(n, a, m))

# Expected output:
3
# count primes that can be expressed as sum of two consecutive primes and 1 | python3 implementation of the approach ; to check if a number is prime or not ; to store possible numbers ; function to return all prime numbers ; if prime [ p ] is not changed , then it is a prime ; update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; function to count all possible prime numbers that can be expressed as the sum of two consecutive primes and one ; all possible prime numbers below n ; 

from math import sqrt
N = 100005
isprime = [True] * N
can = [False] * N


def SieveOfEratosthenes():
    for p in range(2, int(sqrt(N)) + 1):
        if (isprime[p]):
            for i in range(p * p, N, p):
                isprime[i] = False
    primes = []
    for i in range(2, N):
        if (isprime[i]):
            primes .append(i)
    return primes


def Prime_Numbers(n):
    primes = SieveOfEratosthenes()
    for i in range(len(primes) - 1):
        if (primes[i] + primes[i + 1] + 1 < N):
            can[primes[i] + primes[i + 1] + 1] = True
    ans = 0
    for i in range(2, n + 1):
        if (can[i] and isprime[i]):
            ans += 1
    return ans


if __name__ == "__main__":
    n = 50
    print(Prime_Numbers(n))

# Expected output:
5
# sum of bitwise and of all subarrays | python3 program to find sum of bitwise and of all subarrays ; function to find the sum of bitwise and of all subarrays ; variable to store the final sum ; multiplier ; variable to check if counting is on ; variable to store the length of the subarrays ; loop to find the contiguous segments ; updating the multiplier ; returning the sum ; 

import math as mt


def findAndSum(arr, n):
    Sum = 0
    mul = 1
    for i in range(30):
        count_on = 0
        l = 0
        for j in range(n):
            if ((arr[j] & (1 << i)) > 0):
                if (count_on):
                    l += 1
                else:
                    count_on = 1
                    l += 1
            elif (count_on):
                Sum += ((mul * l * (l + 1)) // 2)
                count_on = 0
                l = 0
        if (count_on):
            Sum += ((mul * l * (l + 1)) // 2)
            count_on = 0
            l = 0
        mul *= 2
    return Sum


arr = [7, 1, 1, 5]
n = len(arr)
print(findAndSum(arr, n))

# Expected output:
20
# source to destination in 2 | function that returns true if it is possible to move from source to the destination with the given moves ; 
def isPossible(Sx, Sy, Dx, Dy, x, y):
    if (abs(Sx - Dx) %
        x == 0 and abs(Sy - Dy) %
        y == 0 and (abs(Sx - Dx) / x) %
        2 == (abs(Sy - Dy) / y) %
            2):
        return True
    return False


Sx = 0
Sy = 0
Dx = 0
Dy = 0
x = 3
y = 4
if (isPossible(Sx, Sy, Dx, Dy, x, y)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# count of pairs ( x , y ) in an array such that x < y | function to return the number of pairs ( x , y ) such that x < y ; to store the number of valid pairs ; if a valid pair is found ; return the count of valid pairs ; 
def getPairs(a):
    count = 0
    for i in range(len(a)):
        for j in range(len(a)):
            if (a[i] < a[j]):
                count += 1
    return count


if __name__ == "__main__":
    a = [2, 4, 3, 1]
    print(getPairs(a))

# Expected output:
6
# composite numbers with digit sum 1 | function that returns true if number n is a composite number ; corner cases ; this is checked so that we can skip middle five numbers in below loop ; function that returns true if the eventual digit sum of number nm is 1 ; loop till the sum is not single digit number ; intitialize the sum as zero ; find the sum of digits ; if sum is eventually 1 ; function to print the required numbers from the given range ; if i is one of the required numbers ; 
def isComposite(n):
    if (n <= 1):
        return False
    if (n <= 3):
        return False
    if (n % 2 == 0 or n % 3 == 0):
        return True
    i = 5
    while (i * i <= n):
        if (n % i == 0 or n % (i + 2) == 0):
            return True
        i = i + 6
    return False


def isDigitSumOne(nm):
    while (nm > 9):
        sum_digit = 0
        while (nm != 0):
            digit = nm % 10
            sum_digit = sum_digit + digit
            nm = nm // 10
        nm = sum_digit
    if (nm == 1):
        return True
    else:
        return False


def printValidNums(m, n):
    for i in range(m, n + 1):
        if (isComposite(i) and isDigitSumOne(i)):
            print(i, end=" ")


l = 10
r = 100
printValidNums(l, r)

# Expected output:
10 28 46 55 64 82 91 100
# determine the count of leaf nodes in an n | function to calculate leaf nodes in n - ary tree ; 
def calcNodes(N, I):
    result = 0
    result = I * (N - 1) + 1
    return result


if __name__ == '__main__':
    N = 5
    I = 2
    print("Leaf nodes = ", calcNodes(N, I))

# Expected output:
Leaf nodes =  9
# find the values of x and y in the given equations | function to find the values of x and y ; base condition ; required answer ; 
def findValues(a, b):
    if ((a - b) % 2 == 1):
        print("-1")
        return
    print((a - b) // 2, (a + b) // 2)


a = 12
b = 8
findValues(a, b)

# Expected output:
2 10
# program to implement inverse interpolation using lagrange formula | consider a structure to keep each pair of x and y together ; function to calculate the inverse interpolation ; initialize final x ; calculate each term of the given formula ; add term to final result ; 

class Data:
    def __init__(self, x, y):
        self .x = x
        self .y = y


def inv_interpolate(d: list, n: int, y: float) -> float:
    x = 0
    for i in range(n):
        xi = d[i].x
        for j in range(n):
            if j != i:
                xi = (xi * (y - d[j].y) / (d[i].y - d[j].y))
        x += xi
    return x


if __name__ == "__main__":
    d = [Data(1.27, 2.3), Data(2.25, 2.95), Data(2.5, 3.5), Data(3.6, 5.1)]
    n = 4
    y = 4.5
    print("Value of x at y = 4.5 :", round(inv_interpolate(d, n, y), 5))

# Expected output:
Value of x at y = 4.5 : 2.79501
# count triplet pairs ( a , b , c ) of points in 2 | function to return the count of possible triplets ; insert all the points in a set ; if the mid point exists in the set ; return the count of valid triplets ; 
def countTriplets(n, points):
    pts = []
    ct = 0
    for i in range(n):
        pts .append(points[i])
    for i in range(n):
        for j in range(i + 1, n):
            x = points[i][0] + points[j][0]
            y = points[i][1] + points[j][1]
            if (x % 2 == 0 and y % 2 == 0):
                if [x // 2, y // 2] in pts:
                    ct += 1
    return ct


if __name__ == "__main__":
    points = [[1, 1], [2, 2], [3, 3]]
    n = len(points)
    print(countTriplets(n, points))

# Expected output:
1
# concentration of juice after mixing n glasses in equal proportion | function to return the concentration of the resultant mixture ; 
def mixtureConcentration(n, p):
    res = 0
    for i in range(n):
        res += p[i]
    res /= n
    return res


arr = [0, 20, 20]
n = len(arr)
print(round(mixtureConcentration(n, arr), 4))

# Expected output:
13.3333
# numbers of length n having digits a and b and whose sum of digits contain only digits a and b | python 3 implementation of the approach ; function that returns true if the num contains a and b digits only ; modular exponentiation ; function to return the modular inverse of x modulo mod ; function to return the required count of numbers ; generating factorials of all numbers ; generating inverse of factorials modulo mod of all numbers ; keeping a as largest number ; iterate over all possible values of s and if it is a valid s then proceed further ; check for invalid cases in the equation ; find answer using combinatorics ; add this result to final answer ; 

MAX = 100005
MOD = 1000000007


def check(num, a, b):
    while (num):
        rem = num % 10
        num = int(num / 10)
        if (rem != a and rem != b):
            return 0
    return 1


def power(x, y):
    ans = 1
    while (y):
        if (y & 1):
            ans = (ans * x) % MOD
        y >>= 1
        x = (x * x) % MOD
    return ans % MOD


def modInverse(x):
    return power(x, MOD - 2)


def countNumbers(n, a, b):
    fact = [0 for i in range(MAX)]
    inv = [0 for i in range(MAX)]
    ans = 0
    fact[0] = 1
    for i in range(1, MAX, 1):
        fact[i] = (1 * fact[i - 1] * i)
        fact[i] %= MOD
    inv[MAX - 1] = modInverse(fact[MAX - 1])
    i = MAX - 2
    while (i >= 0):
        inv[i] = (inv[i + 1] * (i + 1))
        inv[i] %= MOD
        i -= 1
    if (a < b):
        temp = a
        a = b
        b = temp
    for s in range(n, 9 * n + 1, 1):
        if (check(s, a, b) == 0):
            continue
        if (s < n * b or (s - n * b) % (a - b) != 0):
            continue
        numDig = int((s - n * b) / (a - b))
        if (numDig > n):
            continue
        curr = fact[n]
        curr = (curr * inv[numDig]) % MOD
        curr = (curr * inv[n - numDig]) % MOD
        ans = (ans + curr) % MOD
    return ans


if __name__ == '__main__':
    n = 3
    a = 1
    b = 3
    print(countNumbers(n, a, b))

# Expected output:
1
# number of elements with even factors in the given range | function to count the perfect squares ; 
def countOddSquares(n, m):
    return (int(pow(m, 0.5)) - int(pow(n - 1, 0.5)))


if __name__ == "__main__":
    n = 5
    m = 100
    print("Count is", (m - n + 1) - countOddSquares(n, m))

# Expected output:
Count is 88
# total position where king can reach on a chessboard in exactly m moves | function to return the number of squares that the king can reach in the given number of moves ; calculate initial and final coordinates ; since chessboard is of size 8 x8 so if any coordinate is less than 1 or greater than 8 make it 1 or 8. ; calculate total positions ; 
def Square(row, column, moves):
    a = 0
    b = 0
    c = 0
    d = 0
    total = 0
    a = row - moves
    b = row + moves
    c = column - moves
    d = column + moves
    if (a < 1):
        a = 1
    if (c < 1):
        c = 1
    if (b > 8):
        b = 8
    if (d > 8):
        d = 8
    total = (b - a + 1) * (d - c + 1) - 1
    return total


if __name__ == "__main__":
    R = 4
    C = 5
    M = 2
    print(Square(R, C, M))

# Expected output:
24
# find m | function to find the m - th number whosesum till one digit is n ; 
def findNumber(n, m):
    num = (m - 1) * 9 + n
    return num


if __name__ == "__main__":
    n = 2
    m = 5
    print(findNumber(n, m))

# Expected output:
38
# check if a number can be represented as a sum of 2 triangular numbers | function to check if it is possible or not ; store all triangular numbers up to n in a set ; check if a pair exists ; 
def checkTriangularSumRepresentation(n):
    tri = list()
    i = 1
    while (1):
        x = i * (i + 1) // 2
        if (x >= n):
            break
        tri .append(x)
        i += 1
    for tm in tri:
        if n - tm in tri:
            return True
    return False


if __name__ == "__main__":
    n = 24
    if checkTriangularSumRepresentation(n):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes