giulio98/xlcost-single-prompt huggingface dataset:
# leaf nodes from preorder of a binary search tree | binary search ; poto the index in preorder . ; function to prleaf nodes by doing preorder traversal of tree using preorder and inorder arrays . ; if l == r , therefore no right or left subtree . so , it must be leaf node , print it . ; if array is out of bound , return . ; finding the index of preorder element in inorder array using binary search . ; incrementing the index . ; finding on the left subtree . ; finding on the right subtree . ; finds leaf nodes from given preorder traversal . ; to store inorder traversal ; copy the preorder into another array . ; finding the inorder by sorting the array . ; print the leaf nodes . ; 
def binarySearch(inorder, l, r, d):
    mid = (l + r) >> 1
    if (inorder[mid] == d):
        return mid
    elif (inorder[mid] > d):
        return binarySearch(inorder, l, mid - 1, d)
    else:
        return binarySearch(inorder, mid + 1, r, d)
    ind = [0]


def leafNodesRec(preorder, inorder, l, r, ind, n):
    if (l == r):
        print(inorder[l], end=" ")
        ind[0] = ind[0] + 1
        return
    if (l < 0 or l > r or r >= n):
        return
    loc = binarySearch(inorder, l, r, preorder[ind[0]])
    ind[0] = ind[0] + 1
    leafNodesRec(preorder, inorder, l, loc - 1, ind, n)
    leafNodesRec(preorder, inorder, loc + 1, r, ind, n)


def leafNodes(preorder, n):
    inorder = [0] * n
    for i in range(n):
        inorder[i] = preorder[i]
    inorder .sort()
    ind = [0]
    leafNodesRec(preorder, inorder, 0, n - 1, ind, n)


preorder = [890, 325, 290, 530, 965]
n = len(preorder)
leafNodes(preorder, n)

# Expected output:
290 530 965
# leaf nodes from preorder of a binary search tree | print the leaf node from the given preorder of bst . ; since rightmost element is always leaf node . ; 
def leafNode(preorder, n):
    s = []
    i = 0
    for j in range(1, n):
        found = False
        if preorder[i] > preorder[j]:
            s .append(preorder[i])
        else:
            while len(s) != 0:
                if preorder[j] > s[-1]:
                    s .pop(-1)
                    found = True
                else:
                    break
        if found:
            print(preorder[i], end=" ")
        i += 1
    print(preorder[n - 1])


if __name__ == '__main__':
    preorder = [890, 325, 290, 530, 965]
    n = len(preorder)
    leafNode(preorder, n)

# Expected output:
290 530 965
# leaf nodes from preorder of a binary search tree ( using recursion ) | print the leaf node from the given preorder of bst . ; 
def isLeaf(pre, i, n, Min, Max):
    if i[0] >= n:
        return False
    if pre[i[0]] > Min and pre[i[0]] < Max:
        i[0] += 1
        left = isLeaf(pre, i, n, Min, pre[i[0] - 1])
        right = isLeaf(pre, i, n, pre[i[0] - 1], Max)
        if left == False and right == False:
            print(pre[i[0] - 1], end=" ")
        return True
    return False


def printLeaves(preorder, n):
    i = [0]
    INT_MIN, INT_MAX = -999999999999, 999999999999
    isLeaf(preorder, i, n, INT_MIN, INT_MAX)


if __name__ == '__main__':
    preorder = [890, 325, 290, 530, 965]
    n = len(preorder)
    printLeaves(preorder, n)

# Expected output:
290 530 965
# minimum possible value of | ai + aj | function for finding pairs and min value ; initialize smallest and count ; iterate over all pairs ; is abs value is smaller than smallest update smallest and reset count to 1 ; if abs value is equal to smallest increment count value ; print result ; 
def pairs(arr, n, k):
    smallest = 999999999999
    count = 0
    for i in range(n):
        for j in range(i + 1, n):
            if abs(arr[i] + arr[j] - k) < smallest:
                smallest = abs(arr[i] + arr[j] - k)
                count = 1
            elif abs(arr[i] + arr[j] - k) == smallest:
                count += 1
    print("Minimal Value = ", smallest)
    print("Total Pairs = ", count)


if __name__ == '__main__':
    arr = [3, 5, 7, 5, 1, 9, 9]
    k = 12
    n = len(arr)
    pairs(arr, n, k)

# Expected output:
Minimal Value =  0
Total Pairs =  4
# sum of middle row and column in matrix | python program to find sum of middle row and column in matrix ; loop for sum of row ; loop for sum of column ; 
def middlesum(mat, n):
    row_sum = 0
    col_sum = 0
    for i in range(n):
        row_sum += mat[n // 2][i]
    print("Sum of middle row = ", row_sum)
    for i in range(n):
        col_sum += mat[i][n // 2]
    print("Sum of middle column = ", col_sum)


mat = [[2, 5, 7], [3, 7, 2], [5, 6, 9]]
middlesum(mat, 3)

# Expected output:
Sum of middle row =  12
Sum of middle column =  18
# program to check involutory matrix | program to implement involutory matrix . ; function for matrix multiplication . ; function to check involutory matrix . ; multiply function call . ; 

N = 3


def multiply(mat, res):
    for i in range(N):
        for j in range(N):
            res[i][j] = 0
            for k in range(N):
                res[i][j] += mat[i][k] * mat[k][j]
    return res


def InvolutoryMatrix(mat):
    res = [[0 for i in range(N)]for j in range(N)]
    res = multiply(mat, res)
    for i in range(N):
        for j in range(N):
            if (i == j and res[i][j] != 1):
                return False
            if (i != j and res[i][j] != 0):
                return False
    return True


mat = [[1, 0, 0], [0, -1, 0], [0, 0, -1]]
if (InvolutoryMatrix(mat)):
    print("Involutory Matrix")
else:
    print("Not Involutory Matrix")

# Expected output:
Involutory Matrix
# interchange elements of first and last rows in matrix | python code to swap the element of first and last row and display the result ; swapping of element between first and last rows ; 
def interchangeFirstLast(mat, n, m):
    rows = n
    for i in range(n):
        t = mat[0][i]
        mat[0][i] = mat[rows - 1][i]
        mat[rows - 1][i] = t


mat = [[8, 9, 7, 6], [4, 7, 6, 5], [3, 2, 1, 8], [9, 9, 7, 7]]
n = 4
m = 4
interchangeFirstLast(mat, n, m)
for i in range(n):
    for j in range(m):
        print(mat[i][j], end=" ")
    print("")

# Expected output:
9 9 7 7 
4 7 6 5 
3 2 1 8 
8 9 7 6
# row wise sorting in 2d array | python3 code to sort 2d matrix row - wise ; loop for rows of matrix ; loop for column of matrix ; loop for comparison and swapping ; swapping of elements ; printing the sorted matrix ; 
def sortRowWise(m):
    for i in range(len(m)):
        for j in range(len(m[i])):
            for k in range(len(m[i]) - j - 1):
                if (m[i][k] > m[i][k + 1]):
                    t = m[i][k]
                    m[i][k] = m[i][k + 1]
                    m[i][k + 1] = t
    for i in range(len(m)):
        for j in range(len(m[i])):
            print(m[i][j], end=" ")
        print()


m = [[9, 8, 7, 1], [7, 3, 0, 2], [9, 5, 3, 2], [6, 3, 1, 2]]
sortRowWise(m)

# Expected output:
1 7 8 9 
0 2 3 7 
2 3 5 9 
1 2 3 6
# row wise sorting in 2d array | python3 code to sort 2d matrix row - wise ; one by one sort individual rows . ; printing the sorted matrix ; 
def sortRowWise(m):
    for i in range(len(m)):
        m[i].sort()
    for i in range(len(m)):
        for j in range(len(m[i])):
            print(m[i][j], end=" ")
        print()
    return 0


m = [[9, 8, 7, 1], [7, 3, 0, 2], [9, 5, 3, 2], [6, 3, 1, 2]]
sortRowWise(m)

# Expected output:
1 7 8 9 
0 2 3 7 
2 3 5 9 
1 2 3 6
# Program for Markov matrix | Python 3 code to check Markov Matrix ; Outer loop to access rows and inner to access columns ; Find sum of current row ; Matrix to check ; Calls the function check ( )
def checkMarkov(m):
    for i in range(0, len(m)):
        sm = 0
        for j in range(0, len(m[i])):
            sm = sm + m[i][j]
        if (sm != 1):
            return False
    return True


m = [[0, 0, 1], [0.5, 0, 0.5], [1, 0, 0]]
if (checkMarkov(m)):
    print(" yes ")
else:
    print(" no ")

# Expected output:
 yes
# program to check diagonal matrix and scalar matrix | python3 program to check if matrix is diagonal matrix or not . ; function to check matrix is diagonal matrix or not . ; condition to check other elements except main diagonal are zero or not . ; 

N = 4


def isDiagonalMatrix(mat):
    for i in range(0, N):
        for j in range(0, N):
            if ((i != j) and (mat[i][j] != 0)):
                return False
    return True


mat = [[4, 0, 0, 0], [0, 7, 0, 0], [0, 0, 5, 0], [0, 0, 0, 1]]
if (isDiagonalMatrix(mat)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# program to check diagonal matrix and scalar matrix | program to check matrix is scalar matrix or not . ; function to check matrix is scalar matrix or not . ; check all elements except main diagonal are zero or not . ; check all diagonal elements are same or not . ; 

N = 4


def isScalarMatrix(mat):
    for i in range(0, N):
        for j in range(0, N):
            if ((i != j) and (mat[i][j] != 0)):
                return False
    for i in range(0, N - 1):
        if (mat[i][i] != mat[i + 1][i + 1]):
            return False
    return True


mat = [[2, 0, 0, 0], [0, 2, 0, 0], [0, 0, 2, 0], [0, 0, 0, 2]]
if (isScalarMatrix(mat)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# check given matrix is magic square or not | python3 program to check whether a given matrix is magic matrix or not ; returns true if mat [ ] [ ] is magic square , else returns false . ; calculate the sum of the prime diagonal ; the secondary diagonal ; for sums of rows ; check if every row sum is equal to prime diagonal sum ; for sums of columns ; check if every column sum is equal to prime diagonal sum ; 

N = 3


def isMagicSquare(mat):
    s = 0
    for i in range(0, N):
        s = s + mat[i][i]
    s2 = 0
    for i in range(0, N):
        s2 = s2 + mat[i][N - i - 1]
    if (s != s2):
        return False
    for i in range(0, N):
        rowSum = 0
        for j in range(0, N):
            rowSum += mat[i][j]
        if (rowSum != s):
            return False
    for i in range(0, N):
        colSum = 0
        for j in range(0, N):
            colSum += mat[j][i]
        if (s != colSum):
            return False
    return True


mat = [[2, 7, 6], [9, 5, 1], [4, 3, 8]]
if (isMagicSquare(mat)):
    print("Magic Square")
else:
    print("Not a magic Square")

# Expected output:
Magic Square
# count sub | function to count all sub - arrays divisible by k ; create auxiliary hash array to count frequency of remainders ; traverse original array and compute cumulative sum take remainder of this current cumulative sum and increase count by 1 for this remainder in mod array ; as the sum can be negative , taking modulo twice ; initialize result ; traverse mod ; if there are more than one prefix subarrays with a particular mod value . ; add the subarrays starting from the arr [ i ] which are divisible by k itself ; function to count all sub - matrices having sum divisible by the value 'k   ; variable to store the final output ; set the left column ; set the right column for the left column set by outer loop ; calculate sum between current left and right for every row 'i   ; count number of subarrays in temp having sum divisible by ' k ' and then add it to 'tot_count   ; required count of sub - matrices having sum divisible by 'k   ; 
def subCount(arr, n, k):
    mod = [0] * k
    cumSum = 0
    for i in range(0, n):
        cumSum = cumSum + arr[i]
        mod[((cumSum % k) + k) % k] = mod[((cumSum % k) + k) % k] + 1
    result = 0
    for i in range(0, k):
        if (mod[i] > 1):
            result = result + int((mod[i] * (mod[i] - 1)) / 2)
    result = result + mod[0]
    return result


def countSubmatrix(mat, n, k):
    tot_count = 0
    temp = [0] * n
    for left in range(0, n - 1):
        for right in range(left, n):
            for i in range(0, n):
                temp[i] = (temp[i] + mat[i][right])
            tot_count = (tot_count + subCount(temp, n, k))
    return tot_count


mat = [[5, -1, 6], [-2, 3, 8], [7, 4, -9]]
n = 3
k = 4
print("Count = {}".format(countSubmatrix(mat, n, k)))

# Expected output:
Count = 6
# count frequency of k in a matrix of size n where matrix ( i , j ) = i + j | python program to find the frequency of k in matrix where m ( i , j ) = i + j ; 

import math


def find(n, k):
    if (n + 1 >= k):
        return (k - 1)
    else:
        return (2 * n + 1 - k)


n = 4
k = 7
freq = find(n, k)
if (freq < 0):
    print(" element not exist")
else:
    print(" Frequency of ", k, " is ", freq)

# Expected output:
 Frequency of  7  is  2
# given 1 ' s , ▁ 2' s , 3 ' s ▁ . . . . . . k ' s print them in zig zag way . | function that prints given number of 1 ' s , ▁ 2' s , 3 ' s ▁ . . . . k ' s in zig - zag way . ; two - dimensional array to store numbers . ; for even row . ; for each column . ; storing element . ; decrement element at kth index . ; if array contains zero then increment index to make this next index ; for odd row . ; for each column . ; storing element . ; decrement element at kth index . ; if array contains zero then increment index to make this next index . ; printing the stored elements . ; 
def ZigZag(rows, columns, numbers):
    k = 0
    arr = [[0 for i in range(columns)]for j in range(rows)]
    for i in range(rows):
        if (i % 2 == 0):
            j = 0
            while j < columns and numbers[k] > 0:
                arr[i][j] = k + 1
                numbers[k] -= 1
                if numbers[k] == 0:
                    k += 1
                j += 1
        else:
            j = columns - 1
            while j >= 0 and numbers[k] > 0:
                arr[i][j] = k + 1
                numbers[k] -= 1
                if numbers[k] == 0:
                    k += 1
                j -= 1
    for i in arr:
        for j in i:
            print(j, end=" ")
        print()


rows = 4
columns = 5
Numbers = [3, 4, 2, 2, 3, 1, 5]
ZigZag(rows, columns, Numbers)

# Expected output:
1 1 1 2 2 
4 3 3 2 2 
4 5 5 5 6 
7 7 7 7 7
# maximum product of 4 adjacent elements in matrix | python3 program to find out the maximum product in the matrix which four elements are adjacent to each other in one direction ; function to find max product ; iterate the rows . ; iterate the columns . ; check the maximum product in horizontal row . ; check the maximum product in vertical row . ; check the maximum product in diagonal going through down - right ; check the maximum product in diagonal going through up - right ; 

n = 5


def FindMaxProduct(arr, n):
    max = 0
    for i in range(n):
        for j in range(n):
            if ((j - 3) >= 0):
                result = (arr[i][j] * arr[i][j - 1] *
                          arr[i][j - 2] * arr[i][j - 3])
                if (max < result):
                    max = result
            if ((i - 3) >= 0):
                result = (arr[i][j] * arr[i - 1][j] *
                          arr[i - 2][j] * arr[i - 3][j])
                if (max < result):
                    max = result
            if ((i - 3) >= 0 and (j - 3) >= 0):
                result = (arr[i][j] * arr[i - 1][j - 1] *
                          arr[i - 2][j - 2] * arr[i - 3][j - 3])
                if (max < result):
                    max = result
            if ((i - 3) >= 0 and (j - 1) <= 0):
                result = (arr[i][j] * arr[i - 1][j + 1] *
                          arr[i - 2][j + 2] * arr[i - 3][j + 3])
                if (max < result):
                    max = result
    return max


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

# Expected output:
3024
# minimum flip required to make binary matrix symmetric | python3 code to find minimum flip required to make binary matrix symmetric along main diagonal ; return the minimum flip required to make binary matrix symmetric along main diagonal . ; finding the transpose of the matrix ; finding the number of position where element are not same . ; 

N = 3


def minimumflip(mat, n):
    transpose = [[0] * n] * n
    for i in range(n):
        for j in range(n):
            transpose[i][j] = mat[j][i]
    flip = 0
    for i in range(n):
        for j in range(n):
            if transpose[i][j] != mat[i][j]:
                flip += 1
    return int(flip / 2)


n = 3
mat = [[0, 0, 1], [1, 1, 1], [1, 0, 0]]
print(minimumflip(mat, n))

# Expected output:
2
# minimum flip required to make binary matrix symmetric | python3 code to find minimum flip required to make binary matrix symmetric along main diagonal ; return the minimum flip required to make binary matrix symmetric along main diagonal . ; comparing elements across diagonal ; 

N = 3


def minimumflip(mat, n):
    flip = 0
    for i in range(n):
        for j in range(i):
            if mat[i][j] != mat[j][i]:
                flip += 1
    return flip


n = 3
mat = [[0, 0, 1], [1, 1, 1], [1, 0, 0]]
print(minimumflip(mat, n))

# Expected output:
2
# frequencies of even and odd numbers in a matrix | python program to find the frequency of even and odd numbers in a matrix ; function for calculating frequency ; modulo by 2 to check even and odd ; print frequency of numbers ; 

MAX = 100


def freq(ar, m, n):
    even = 0
    odd = 0
    for i in range(m):
        for j in range(n):
            if ((ar[i][j] % 2) == 0):
                even += 1
            else:
                odd += 1
    print(" Frequency of odd number =", odd)
    print(" Frequency of even number =", even)


m = 3
n = 3
array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
freq(array, m, n)

# Expected output:
 Frequency of odd number = 5
 Frequency of even number = 4
# center element of matrix equals sums of half diagonals | python 3 program to check if the center element is equal to the individual sum of all the half diagonals ; function to check center element is equal to the individual sum of all the half diagonals ; find sums of half diagonals ; 

MAX = 100


def HalfDiagonalSums(mat, n):
    diag1_left = 0
    diag1_right = 0
    diag2_left = 0
    diag2_right = 0
    i = 0
    j = n - 1
    while i < n:
        if (i < n // 2):
            diag1_left += mat[i][i]
            diag2_left += mat[j][i]
        elif (i > n // 2):
            diag1_right += mat[i][i]
            diag2_right += mat[j][i]
        i += 1
        j -= 1
    return (diag1_left == diag2_right and diag2_right == diag2_left and diag1_right ==
            diag2_left and diag2_right == mat[n // 2][n // 2])


if __name__ == "__main__":
    a = [[2, 9, 1, 4, -2], [6, 7, 2, 11, 4],
         [4, 2, 9, 2, 4], [1, 9, 2, 4, 4], [0, 2, 4, 2, 5]]
    print("Yes")if (HalfDiagonalSums(a, 5))else print("No")

# Expected output:
Yes
# program for identity matrix | python code to print identity matrix function to print identity matrix ; here end is used to stay in same line ; 
def Identity(size):
    for row in range(0, size):
        for col in range(0, size):
            if (row == col):
                print("1 ", end=" ")
            else:
                print("0 ", end=" ")
        print()


size = 5
Identity(size)

# Expected output:
1  0  0  0  0  
0  1  0  0  0  
0  0  1  0  0  
0  0  0  1  0  
0  0  0  0  1
# program for identity matrix | python3 program to check if a given matrix is identity ; 

MAX = 100


def isIdentity(mat, N):
    for row in range(N):
        for col in range(N):
            if (row == col and mat[row][col] != 1):
                return False
            elif (row != col and mat[row][col] != 0):
                return False
    return True


N = 4
mat = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
if (isIdentity(mat, N)):
    print("Yes ")
else:
    print("No ")

# Expected output:
Yes
# ways of filling matrix such that product of all rows and all columns are equal to unity | returns a raised power t under modulo mod ; counting number of ways of filling the matrix ; function calculating the answer ; if sum of numbers of rows and columns is odd i . e ( n + m ) % 2 == 1 and k = - 1 then there are 0 ways of filiing the matrix . ; if there is one row or one column then there is only one way of filling the matrix ; if the above cases are not followed then we find ways to fill the n - 1 rows and m - 1 columns which is 2 ^ ( ( m - 1 ) * ( n - 1 ) ) . ; 
def modPower(a, t):
    now = a
    ret = 1
    mod = 100000007
    while (t):
        if (t & 1):
            ret = now * (ret % mod)
        now = now * (now % mod)
        t >>= 1
    return ret


def countWays(n, m, k):
    mod = 100000007
    if (k == -1 and ((n + m) % 2 == 1)):
        return 0
    if (n == 1 or m == 1):
        return 1
    return (modPower(modPower(2, n - 1), m - 1) % mod)


n = 2
m = 7
k = 1
print(countWays(n, m, k))

# Expected output:
64
# find all rectangles filled with 0 | python program to find all rectangles filled with 0 ; flag to check column edge case , initializing with 0 ; flag to check row edge case , initializing with 0 ; loop breaks where first 1 encounters ; set the flag ; pass because already processed ; loop breaks where first 1 encounters ; set the flag ; fill rectangle elements with any number so that we can exclude next time ; when end point touch the boundary ; when end point touch the boundary ; retrieving the column size of array ; output array where we are going to store our output ; it will be used for storing start and end location in the same index ; storing initial position of rectangle ; will be used for the last position ; 
def findend(i, j, a, output, index):
    x = len(a)
    y = len(a[0])
    flagc = 0
    flagr = 0
    for m in range(i, x):
        if a[m][j] == 1:
            flagr = 1
            break
        if a[m][j] == 5:
            pass
        for n in range(j, y):
            if a[m][n] == 1:
                flagc = 1
                break
            a[m][n] = 5
    if flagr == 1:
        output[index].append(m - 1)
    else:
        output[index].append(m)
    if flagc == 1:
        output[index].append(n - 1)
    else:
        output[index].append(n)


def get_rectangle_coordinates(a):
    size_of_array = len(a)
    output = []
    index = -1
    for i in range(0, size_of_array):
        for j in range(0, len(a[0])):
            if a[i][j] == 0:
                output .append([i, j])
                index = index + 1
                findend(i, j, a, output, index)
    print(output)


tests = [
    [
        1, 1, 1, 1, 1, 1, 1], [
            1, 1, 1, 1, 1, 1, 1], [
                1, 1, 1, 0, 0, 0, 1], [
                    1, 0, 1, 0, 0, 0, 1], [
                        1, 0, 1, 1, 1, 1, 1], [
                            1, 0, 1, 0, 0, 0, 0], [
                                1, 1, 1, 0, 0, 0, 1], [
                                    1, 1, 1, 1, 1, 1, 1]]
get_rectangle_coordinates(tests)

# Expected output:
[[2, 3, 3, 5], [3, 1, 5, 1], [5, 3, 6, 5]]
# search in a row wise and column wise sorted matrix | searches the element x in mat [ ] [ ] . if the element is found , then prints its position and returns true , otherwise prints " not ▁ found " and returns false ; traverse through the matrix ; if the element is found ; 
def search(mat, n, x):
    if (n == 0):
        return -1
    for i in range(n):
        for j in range(n):
            if (mat[i][j] == x):
                print("Element found at (", i, ",", j, ")")
                return 1
    print(" Element not found")
    return 0


mat = [[10, 20, 30, 40], [15, 25, 35, 45], [27, 29, 37, 48], [32, 33, 39, 50]]
search(mat, 4, 29)

# Expected output:
Element found at ( 2 , 1 )
# search in a row wise and column wise sorted matrix | searches the element x in mat [ ] [ ] . if the element is found , then prints its position and returns true , otherwise prints " not ▁ found " and returns false ; set indexes for top right element ; if mat [ i ] [ j ] < x ; if ( i == n j == - 1 ) ; 
def search(mat, n, x):
    i = 0
    j = n - 1
    while (i < n and j >= 0):
        if (mat[i][j] == x):
            print("n Found at ", i, ", ", j)
            return 1
        if (mat[i][j] > x):
            j -= 1
        else:
            i += 1
    print("Element not found")
    return 0


mat = [[10, 20, 30, 40], [15, 25, 35, 45], [27, 29, 37, 48], [32, 33, 39, 50]]
search(mat, 4, 29)

# Expected output:
n Found at  2 ,  1