giulio98/xlcost-single-prompt huggingface dataset:
# difference between sums of odd level and even level nodes of a binary tree | a binary tree node ; the main function that returns difference between odd and even level nodes ; base case ; difference for root is root 's data - difference for  left subtree - difference for right subtree ; 

class Node:
    def __init__(self, data):
        self .data = data
        self .left = None
        self .right = None


def getLevelDiff(root):
    if root is None:
        return 0
    return (root .data - getLevelDiff(root .left) - getLevelDiff(root .right))


root = Node(5)
root .left = Node(2)
root .right = Node(6)
root .left .left = Node(1)
root .left .right = Node(4)
root .left .right .left = Node(3)
root .right .right = Node(8)
root .right .right .right = Node(9)
root .right .right .left = Node(7)
print("%d is the required difference" % (getLevelDiff(root)))

# Expected output:
-9 is the required difference
# Sum of all leaf nodes of binary tree | Class for node creation ; constructor ; Utility function to calculate the sum of all leaf nodes ; add root data to sum if root is a leaf node ; propagate recursively in left and right subtree ; Binary tree Fromation ; Variable to store the sum of leaf nodes

class Node:
    def __init__(self, data):
        self .data = data
        self .left = None
        self .right = None


def leafSum(root):
    global total
    if root is None:
        return
    if (root .left is None and root .right is None):
        total += root .data
    leafSum(root .left)
    leafSum(root .right)


if __name__ == '__main__':
    root = Node(1)
    root .left = Node(2)
    root .left .left = Node(4)
    root .left .right = Node(5)
    root .right = Node(3)
    root .right .right = Node(7)
    root .right .left = Node(6)
    root .right .left .right = Node(8)
    total = 0
    leafSum(root)
    print(total)

# Expected output:
24
# Inorder Tree Traversal without recursion and without stack ! | A binary tree node ; Generator function for iterative inorder tree traversal ; Find the inorder predecessor of current ; Make current as right child of its inorder predecessor ; Revert the changes made in the ' if ' part to restore the original tree . i . e . , fix the right child of predecessor ; Constructed binary tree is 1 / \ 2 3 / \ 4 5

class Node:
    def __init__(self, data, left=None, right=None):
        self .data = data
        self .left = left
        self .right = right


def morris_traversal(root):
    current = root
    while current is not None:
        if current .left is None:
            yield current .data
            current = current .right
        else:
            pre = current .left
            while pre .right is not None and pre .right is not current:
                pre = pre .right
            if pre .right is None:
                pre .right = current
                current = current .left
            else:
                pre .right = None
                yield current .data
                current = current .right


root = Node(1, right=Node(3), left=Node(2, left=Node(4), right=Node(5)))
for v in morris_traversal(root):
    print(v, end=' ')

# Expected output:
4 2 5 1 3
# sum of leaf nodes at minimum level | python3 implementation to find the sum of leaf node at minimum level ; structure of a node in binary tree ; function to find the sum of leaf nodes at minimum level ; if tree is empty ; if there is only root node ; queue used for level order traversal ; push rioot node in the queue ; count no . of nodes present at current level ; traverse current level nodes ; get front element from ' q ' ; if node is leaf node ; accumulate data to ' sum ' ; set flag = 1 to signify that we have encountered the minimum level ; if top 's left or right child exist  push them to queue ; return the sum ; 

from collections import deque


class Node:
    def __init__(self, data):
        self .data = data
        self .left = None
        self .right = None


def sumOfLeafNodesAtLeafLevel(root):
    if not root:
        return 0
    if not root .left and not root .right:
        return root .data
    Queue = deque()
    sum = f = 0
    Queue .append(root)
    while not f:
        nc = len(Queue)
        while nc:
            top = Queue .popleft()
            if not top .left and not top .right:
                sum += top .data
                f = 1
            else:
                if top .left:
                    Queue .append(top .left)
                if top .right:
                    Queue .append(top .right)
            nc -= 1
    return sum


if __name__ == "__main__":
    root = Node(1)
    root .left = Node(2)
    root .right = Node(3)
    root .left .left = Node(4)
    root .left .right = Node(5)
    root .right .left = Node(6)
    root .right .right = Node(7)
    root .left .right .left = Node(8)
    root .right .left .right = Node(9)
    print("Sum = ", sumOfLeafNodesAtLeafLevel(root))

# Expected output:
Sum =  11
# root to leaf path sum equal to a given number | a binary tree node ; given a tree and a sum , return true if there is a path from the root down to a leaf , such that adding up all the values along the path equals the 

class Node:
    def __init__(self, data):
        self .data = data
        self .left = None
        self .right = None


def hasPathSum(node, s):
    if node is None:
        return (s == 0)
    else:
        ans = 0
        subSum = s - node .data
        if (subSum == 0 and node .left is None and node .right is None):
            return True
        if node .left is not None:
            ans = ans or hasPathSum(node .left, subSum)
        if node .right is not None:
            ans = ans or hasPathSum(node .right, subSum)
        return ans


s = 21
root = Node(10)
root .left = Node(8)
root .right = Node(2)
root .left .right = Node(5)
root .left .left = Node(3)
root .right .left = Node(2)
if hasPathSum(root, s):
    print("There is a root-to-leaf path with sum %d" % (s))
else:
    print("There is no root-to-leaf path with sum %d" % (s))

# Expected output:
There is a root-to-leaf path with sum 21
# sum of all the numbers that are formed from root to leaf paths | python program to find sum of all paths from root to leaves a binary tree node ; returs sums of all root to leaf paths . the first parameter is root of current subtree , the second paramete "r is value of the number formed by nodes from root to this node ; base case ; update val ; if current node is leaf , return the current value of val ; recur sum of values for left and right subtree ; a wrapper function over treepathsumutil ( ) ; pass the initial value as 0 as ther is nothing above root ; 

class Node:
    def __init__(self, data):
        self .data = data
        self .left = None
        self .right = None


def treePathsSumUtil(root, val):
    if root is None:
        return 0
    val = (val * 10 + root .data)
    if root .left is None and root .right is None:
        return val
    return (
        treePathsSumUtil(
            root .left,
            val) +
        treePathsSumUtil(
            root .right,
            val))


def treePathsSum(root):
    return treePathsSumUtil(root, 0)


root = Node(6)
root .left = Node(3)
root .right = Node(5)
root .left .left = Node(2)
root .left .right = Node(5)
root .right .right = Node(4)
root .left .right .left = Node(7)
root .left .right .right = Node(4)
print("Sum of all paths is", treePathsSum(root))

# Expected output:
Sum of all paths is 13997
# find root of the tree where children id sum for every node is given | find root of tree where children sum for every node id is given ; every node appears once as an id , and every node except for the root appears once in a sum . so if we subtract all the sums from all the ids , we 're left  with the root id. ; 
def findRoot(arr, n):
    root = 0
    for i in range(n):
        root += (arr[i][0] - arr[i][1])
    return root


if __name__ == '__main__':
    arr = [[1, 5], [2, 0], [3, 0], [4, 0], [5, 5], [6, 5]]
    n = len(arr)
    print(findRoot(arr, n))

# Expected output:
6
# print postorder traversal from given inorder and preorder traversals | a utility function to search x in arr [ ] of size n ; prints postorder traversal from given inorder and preorder traversals ; the first element in pre [ ] is always root , search it in in [ ] to find left and right subtrees ; if left subtree is not empty , print left subtree ; if right subtree is not empty , print right subtree ; print root ; 
def search(arr, x, n):
    for i in range(n):
        if (arr[i] == x):
            return i
    return -1


def printPostOrder(In, pre, n):
    root = search(In, pre[0], n)
    if (root != 0):
        printPostOrder(In, pre[1:n], root)
    if (root != n - 1):
        printPostOrder(In[root + 1:n], pre[root + 1:n], n - root - 1)
    print(pre[0], end=" ")


In = [4, 2, 5, 1, 3, 6]
pre = [1, 2, 4, 5, 3, 6]
n = len(In)
print("Postorder traversal ")
printPostOrder(In, pre, n)

# Expected output:
Postorder traversal 
4 5 2 6 3 1
# lowest common ancestor in a binary tree | set 1 | a binary tree node ; this function returns pointer to lca of two given values n1 and n2 this function assumes that n1 and n2 are present in binary tree ; base case ; if either n1 or n2 matches with root 's key, report  the presence by returning root (note that if a key is  ancestor of other, then the ancestor key becomes lca ; look for keys in left and right subtrees ; if both of the above calls return non - null , then one key is present in once subtree and other is present in other , so this node is the lca ; otherwise check if left subtree or right subtree is lca ; 

class Node:
    def __init__(self, key):
        self .key = key
        self .left = None
        self .right = None


def findLCA(root, n1, n2):
    if root is None:
        return None
    if root .key == n1 or root .key == n2:
        return root
    left_lca = findLCA(root .left, n1, n2)
    right_lca = findLCA(root .right, n1, n2)
    if left_lca and right_lca:
        return root
    return left_lca if left_lca is not None else right_lca


root = Node(1)
root .left = Node(2)
root .right = Node(3)
root .left .left = Node(4)
root .left .right = Node(5)
root .right .left = Node(6)
root .right .right = Node(7)
print("LCA(4,5) = ", findLCA(root, 4, 5).key)
print("LCA(4,6) = ", findLCA(root, 4, 6).key)
print("LCA(3,4) = ", findLCA(root, 3, 4).key)
print("LCA(2,4) = ", findLCA(root, 2, 4).key)

# Expected output:
LCA(4,5) =  2
LCA(4,6) =  1
LCA(3,4) =  1
LCA(2,4) =  2
# lowest common ancestor in a binary tree | set 1 | a binary tree node ; this function retturn pointer to lca of two given values n1 and n2 v1 is set as true by this function if n1 is found v2 is set as true by this function if n2 is found ; base case ; if either n1 or n2 matches ith root 's key, report  the presence by setting v1 or v2 as true and return  root (note that if a key is ancestor of other, then the ancestor key becomes lca) ; look for keys in left and right subtree ; if both of the above calls return non - null , then one key is present in once subtree and other is present in other , so this node is the lca ; otherwise check if left subtree or right subtree is lca ; returns true if key k is present in tree rooted with root ; this function returns lca of n1 and n2 onlue if both n1 and n2 are present in tree , otherwise returns none ; initialize n1 and n2 as not visited ; find lac of n1 and n2 using the technique discussed above ; returns lca only if both n1 and n2 are present in tree ; else return none ; 

class Node:
    def __init__(self, key):
        self .key = key
        self .left = None
        self .right = None


def findLCAUtil(root, n1, n2, v):
    if root is None:
        return None
    if root .key == n1:
        v[0] = True
        return root
    if root .key == n2:
        v[1] = True
        return root
    left_lca = findLCAUtil(root .left, n1, n2, v)
    right_lca = findLCAUtil(root .right, n1, n2, v)
    if left_lca and right_lca:
        return root
    return left_lca if left_lca is not None else right_lca


def find(root, k):
    if root is None:
        return False
    if (root .key == k or find(root .left, k) or find(root .right, k)):
        return True
    return False


def findLCA(root, n1, n2):
    v = [False, False]
    lca = findLCAUtil(root, n1, n2, v)
    if (v[0] and v[1] or v[0] and find(lca, n2) or v[1] and find(lca, n1)):
        return lca
    return None


root = Node(1)
root .left = Node(2)
root .right = Node(3)
root .left .left = Node(4)
root .left .right = Node(5)
root .right .left = Node(6)
root .right .right = Node(7)
lca = findLCA(root, 4, 5)
if lca is not None:
    print("LCA(4, 5) = ", lca .key)
else:
    print("Keys are not present")
lca = findLCA(root, 4, 10)
if lca is not None:
    print("LCA(4,10) = ", lca .key)
else:
    print("Keys are not present")

# Expected output:
LCA(4, 5) =  2
Keys are not present
# print ancestors of a 

class Node:
    def __init__(self, data):
        self .data = data
        self .left = None
        self .right = None


def printAncestors(root, target):
    if root is None:
        return False
    if root .data == target:
        return True
    if (printAncestors(root .left, target)
            or printAncestors(root .right, target)):
        print(root .data)
        return True
    return False


root = Node(1)
root .left = Node(2)
root .right = Node(3)
root .left .left = Node(4)
root .left .right = Node(5)
root .left .left .left = Node(7)
printAncestors(root, 7)

# Expected output:
4
2
1
# print postorder traversal from given inorder and preorder traversals | python3 program to prpostorder traversal from given inorder and preorder traversals . ; find index of next item in preorder traversal in inorder . ; traverse left tree ; traverse right tree ; prroot node at the end of traversal ; 
def printPost(inn, pre, inStrt, inEnd):
    global preIndex, hm
    if (inStrt > inEnd):
        return
    inIndex = hm[pre[preIndex]]
    preIndex += 1
    printPost(inn, pre, inStrt, inIndex - 1)
    printPost(inn, pre, inIndex + 1, inEnd)
    print(inn[inIndex], end=" ")


def printPostMain(inn, pre, n):
    for i in range(n):
        hm[inn[i]] = i
    printPost(inn, pre, 0, n - 1)


if __name__ == '__main__':
    hm = {}
    preIndex = 0
    inn = [4, 2, 5, 1, 3, 6]
    pre = [1, 2, 4, 5, 3, 6]
    n = len(pre)
    printPostMain(inn, pre, n)

# Expected output:
4 5 2 6 3 1
# coordinates of the last cell in a matrix on which performing given operations exits from the matrix | function to check if the indices ( i , j ) are valid indices in a matrix or not ; cases for invalid cells ; return true if valid ; function to find indices of cells of a matrix from which traversal leads to out of the matrix ; starting from cell ( 0 , 0 ) , traverse in right direction ; stores direction changes ; iterate until the current cell exceeds beyond the matrix ; current index ; if the current cell is 1 ; update arr [ i ] [ j ] = 0 ; update indices according to the direction ; otherwise ; update indices according to the direction ; the exit cooridnates ; number of rows ; number of columns ; 
def issafe(m, n, i, j):
    if i < 0:
        return False
    if j < 0:
        return False
    if i >= m:
        return False
    if j >= n:
        return False
    return True


def endpoints(arr, m, n):
    i = 0
    j = 0
    current_d = 'r'
    rcd = {'l': 'u', 'u': 'r', 'r': 'd', 'd': 'l'}
    while issafe(m, n, i, j):
        current_i = i
        current_j = j
        if arr[i][j] == 1:
            move_in = rcd[current_d]
            arr[i][j] = 0
            if move_in == 'u':
                i -= 1
            elif move_in == 'd':
                i += 1
            elif move_in == 'l':
                j -= 1
            elif move_in == 'r':
                j += 1
            current_d = move_in
        else:
            if current_d == 'u':
                i -= 1
            elif current_d == 'd':
                i += 1
            elif current_d == 'l':
                j -= 1
            elif current_d == 'r':
                j += 1
    return (current_i, current_j)


M = 3
N = 5
arr = [[0, 1, 1, 1, 0], [1, 0, 1, 0, 1], [1, 1, 1, 0, 0], ]
print(endpoints(arr, M, N))

# Expected output:
(2, 0)
# check if a number can be represented as sum of two positive perfect cubes | function to check if n can be represented as sum of two perfect cubes or not ; stores the perfect cubes of first n natural numbers ; traverse the map ; stores first number ; stores second number ; search the pair for the first number to obtain sum n from the map ; if n cannot be represented as sum of two positive perfect cubes ; 
def sumOfTwoPerfectCubes(N):
    cubes = {}
    i = 1
    while i * i * i <= N:
        cubes[i * i * i] = i
        i += 1
    for itr in cubes:
        firstNumber = itr
        secondNumber = N - itr
        if secondNumber in cubes:
            print("True", end="")
            return
    print("False", end="")


N = 28
sumOfTwoPerfectCubes(N)

# Expected output:
True
# count subsets consisting of each element as a factor of the next element in that subset | function to find number of subsets satisfying the given condition ; stores number of required sets ; stores maximum element of arr [ ] that defines the size of sieve ; iterate through the arr [ ] ; if current element > maxe , then update maxe ; declare an array sieve of size n + 1 ; mark all elements corresponding in the array , by one as there will always exists a singleton set ; iterate from range [ 1 , n ] ; if element is present in array ; traverse through all its multiples <= n ; update them if they are present in array ; iterate from the range [ 1 , n ] ; update the value of cnt ; prthe result ; 
def countSets(arr, n):
    cnt = 0
    maxE = -1
    for i in range(n):
        if (maxE < arr[i]):
            maxE = arr[i]
    sieve = [0] * (maxE + 1)
    for i in range(n):
        sieve[arr[i]] = 1
    for i in range(1, maxE + 1):
        if (sieve[i] != 0):
            for j in range(i * 2, maxE + 1, i):
                if (sieve[j] != 0):
                    sieve[j] = (sieve[j] + sieve[i]) % 1000000007
    for i in range(maxE + 1):
        cnt = (cnt % 1000000007 + sieve[i] % 1000000007) % 1000000007
    print(cnt % 1000000007)


if __name__ == '__main__':
    arr = [16, 18, 6, 7, 2, 19, 20, 9]
    N = len(arr)
    countSets(arr, N)

# Expected output:
15
# find the first day of a given year from a base year having first day as monday | function to find the day of 1 st january of y year ; count years between years y and b ; count leap years ; non leap years ; total number of days in the years lying between the years y and b ; actual day ; 
def findDay(Y, B):
    lyear, rest, totaldays, day = 0, 0, 0, 0
    Y = (Y - 1) - B
    lyear = Y // 4
    rest = Y - lyear
    totaldays = (rest * 365) + (lyear * 366) + 1
    day = (totaldays % 7)
    if (day == 0):
        print("Monday")
    elif (day == 1):
        print("Tuesday")
    elif (day == 2):
        print("Wednesday")
    elif (day == 3):
        print("Thursday")
    elif (day == 4):
        print("Friday")
    elif (day == 5):
        print("Saturday")
    elif (day == 6):
        print("Sunday")
    else:
        print("INPUT YEAR IS WRONG!")


if __name__ == '__main__':
    Y = 2020
    B = 1900
    findDay(Y, B)

# Expected output:
Wednesday
# queries to update array elements in a range [ l , r ] to satisfy given conditions | function to prthe array ; function to perform the query in range [ l , r ] such that arr [ i ] += i - l + 1 ; initialize array ; traverse the query array ; stores range in 1 - based index ; update arr1 [ l ] ; update arr1 [ r + 1 ] ; update arr2 [ r + 1 ] ; calculate prefix sum ; traverse the array , arr2 [ ] ; copy arr2 [ ] into arr [ ] ; 
def printArray(arr, N):
    print(*arr)


def modifyArray(arr, N, Q, cntQuery):
    arr1 = [0 for i in range(N + 2)]
    arr2 = [0 for i in range(N + 2)]
    for i in range(cntQuery):
        L = Q[i][0] + 1
        R = Q[i][1] + 1
        arr1[L] += 1
        arr1[R + 1] -= 1
        arr2[R + 1] -= R - L + 1
    for i in range(1, N + 1):
        arr1[i] += arr1[i - 1]
    for i in range(1, N + 1):
        arr2[i] += arr2[i - 1] + arr1[i]
    for i in range(1, N + 1):
        arr[i - 1] = arr2[i]
    printArray(arr, N)


if __name__ == '__main__':
    arr = [0, 0, 0, 0]
    N = len(arr)
    Q = [[1, 3], [0, 1]]
    cntQuery = len(Q)
    modifyArray(arr, N, Q, cntQuery)

# Expected output:
1 3 2 3
# maximize product obtained by taking one element from each array of a given list | function to return the product of 2 numbers ; if any of the two numbers is none ; otherwise , return the product ; function to calculate maximum product by taking only one element from each array present in the list ; find the maximum and minimum present in the current array ; if last index is reached , then return the highest ( positive ) and lowest ( negative ) values ; store the positive and negative products returned by calculating for the remaining arrays ; store highest positive product ; store product of highest with negative ; store product of lowest with positive ; store lowest negative product ; return the maximum positive and minimum negative product ; count of given arrays ; 
def findProduct(number_1, number_2):
    if (number_1 is None or number_2 is None):
        return 0
    else:
        return number_1 * number_2


def calculateProduct(List, index):
    highest = max(List[index])
    lowest = min(List[index])
    if (index + 1 == len(List)):
        if (lowest < 0 and highest >= 0):
            return [highest, lowest]
        elif (lowest <= 0 and highest <= 0):
            return [None, lowest]
        elif (lowest >= 0 and highest >= 0):
            return [highest, None]
    [positive, negative] = calculateProduct(List, index + 1)
    highPos = findProduct(highest, positive)
    highNeg = findProduct(highest, negative)
    lowPos = findProduct(lowest, positive)
    lowNeg = findProduct(lowest, negative)
    if (lowest < 0 and highest >= 0):
        return [max(highPos, lowNeg), min(highNeg, lowPos)]
    elif (lowest <= 0 and highest <= 0):
        return [lowNeg, lowPos]
    elif (lowest >= 0 and highest >= 0):
        return [max(lowPos, highPos), min(lowNeg, highNeg)]


N = 2
arr = [[-3, -4], [1, 2, -3]]
positive, negative = calculateProduct(arr, 0)
print(positive)

# Expected output:
12
# reduce a number n by at most d to maximize count of trailing nines | python3 program for the above approach ; function to find a number with maximum count of trailing nine ; stores count of digits in n ; stores power of 10 ; if last i digits greater than or equal to d ; update res ; update p10 ; 

from math import log10


def maxNumTrailNine(n, d):
    res = n
    cntDigits = int(log10(n) + 1)
    p10 = 10
    for i in range(1, cntDigits + 1):
        if (n % p10 >= d):
            break
        else:
            res = n - n % p10 - 1
        p10 = p10 * 10
    print(res)


if __name__ == '__main__':
    n, d = 1025, 6
    maxNumTrailNine(n, d)

# Expected output:
1019
# split array into minimum number of subsets such that elements of all pairs are present in different subsets at least once | function to find minimum count of ways to split the array into two subset such that elements of each pair occurs in two different subset ; stores minimum count of ways to split array into two subset such that elements of each pair occurs in two different subset ; if n is odd ; 
def MinimumNoOfWays(arr, n):
    min_no_of_ways = 0
    if (n % 2 == 0):
        mini_no_of_ways = n // 2
    else:
        mini_no_of_ways = n // 2 + 1
    return mini_no_of_ways


if __name__ == '__main__':
    arr = [3, 4, 1, 2, 5]
    n = len(arr)
    print(MinimumNoOfWays(arr, n))

# Expected output:
3