giulio98/xlcost-single-prompt huggingface dataset:
# program to find the volume of an irregular tetrahedron | python 3 implementation of above approach ; function to find the volume ; steps to calculate volume of a tetrahedron using formula ; 

from math import *


def findVolume(u, v, w, U, V, W, b):
    uPow = pow(u, 2)
    vPow = pow(v, 2)
    wPow = pow(w, 2)
    UPow = pow(U, 2)
    VPow = pow(V, 2)
    WPow = pow(W, 2)
    a = (4 * (uPow * vPow * wPow) - uPow * pow((vPow + wPow - UPow),
                                               2) - vPow * pow((wPow + uPow - VPow),
                                                               2) - wPow * pow((uPow + vPow - WPow),
                                                                               2) + (vPow + wPow - UPow) * (wPow + uPow - VPow) * (uPow + vPow - WPow))
    vol = sqrt(a)
    vol /= b
    print(round(vol, 4))


if __name__ == "__main__":
    u, v, w = 1000, 1000, 1000
    U, V, W = 3, 4, 5
    b = 12
    findVolume(u, v, w, U, V, W, b)

# Expected output:
1999.9947
# check if it is possible to create a polygon with a given angle | function to check whether it is possible to make a regular polygon with a given angle . ; n denotes the number of sides of polygons possible ; 
def makePolygon(a):
    n = 360 / (180 - a)
    if n == int(n):
        print("YES")
    else:
        print("NO")


if __name__ == "__main__":
    a = 90
    makePolygon(a)

# Expected output:
YES
# finding quadrant of a coordinate with respect to a circle | python3 program to find the quadrant of a given coordinate w . rt . the centre of a circle ; thus function returns the quadrant number ; coincides with center ; outside circle ; 1 st quadrant ; 2 nd quadrant ; 3 rd quadrant ; 4 th quadrant ; coordinates of centre ; radius of circle ; coordinates of the 

import math


def getQuadrant(X, Y, R, PX, PY):
    if (PX == X and PY == Y):
        return 0
    val = (math .pow((PX - X), 2) + math .pow((PY - Y), 2))
    if (val > pow(R, 2)):
        return -1
    if (PX > X and PY >= Y):
        return 1
    if (PX <= X and PY > Y):
        return 2
    if (PX < X and PY <= Y):
        return 3
    if (PX >= X and PY < Y):
        return 4


X = 0
Y = 3
R = 2
PX = 1
PY = 4
ans = getQuadrant(X, Y, R, PX, PY)
if (ans == -1):
    print("Lies Outside the circle")
elif (ans == 0):
    print("Coincides with centre")
else:
    print(ans, "Quadrant")

# Expected output:
1 Quadrant
# hexadecagonal number | function to calculate hexadecagonal number ; 
def hexadecagonalNum(n):
    return ((14 * n * n) - 12 * n) // 2


n = 5
print("%sth Hexadecagonal number : " % n, hexadecagonalNum(n))
n = 9
print("%sth Hexadecagonal number : " % n, hexadecagonalNum(n))

# Expected output:
5th Hexadecagonal number :  145
9th Hexadecagonal number :  513
# maximum points of intersection n circles | returns maximum number of intersections ; 
def intersection(n):
    return n * (n - 1)


print(intersection(3))

# Expected output:
6
# find the perimeter of a cylinder | function to calculate the perimeter of a cylinder ; 
def perimeter(diameter, height):
    return 2 * (diameter + height)


diameter = 5
height = 10
print("Perimeter = ", perimeter(diameter, height))

# Expected output:
Perimeter =  30
# check whether a given point lies inside a rectangle or not | a utility function to calculate area of triangle formed by ( x1 , y1 ) , ( x2 , y2 ) and ( x3 , y3 ) ; a function to check whether point p ( x , y ) lies inside the rectangle formed by a ( x1 , y1 ) , b ( x2 , y2 ) , c ( x3 , y3 ) and d ( x4 , y4 ) ; calculate area of rectangle abcd ; calculate area of triangle pab ; calculate area of triangle pbc ; calculate area of triangle pcd ; calculate area of triangle pad ; check if sum of a1 , a2 , a3 and a4 is same as a ; 
def area(x1, y1, x2, y2, x3, y3):
    return abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0)


def check(x1, y1, x2, y2, x3, y3, x4, y4, x, y):
    A = (area(x1, y1, x2, y2, x3, y3) + area(x1, y1, x4, y4, x3, y3))
    A1 = area(x, y, x1, y1, x2, y2)
    A2 = area(x, y, x2, y2, x3, y3)
    A3 = area(x, y, x3, y3, x4, y4)
    A4 = area(x, y, x1, y1, x4, y4)
    return (A == A1 + A2 + A3 + A4)


if __name__ == '__main__':
    if (check(0, 10, 10, 0, 0, -10, -10, 0, 10, 15)):
        print("yes")
    else:
        print("no")

# Expected output:
no
# pizza cut problem ( or circle division by lines ) | function for finding maximum pieces with n cuts . ; 
def findMaximumPieces(n):
    return int(1 + n * (n + 1) / 2)


print(findMaximumPieces(3))

# Expected output:
7
# klee 's algorithm (length of union of segments of a line) | returns sum of lengths covered by union of given segments ; initialize empty points container ; create a vector to store starting and ending points ; sorting all points by point value ; initialize result as 0 ; to keep track of counts of current open segments ( starting point is processed , but ending point is not ) ; traverse through all points ; if there are open points , then we add the difference between previous and current point . ; if this is an ending point , reduce , count of open points . ; 
def segmentUnionLength(segments):
    n = len(segments)
    points = [None] * (n * 2)
    for i in range(n):
        points[i * 2] = (segments[i][0], False)
        points[i * 2 + 1] = (segments[i][1], True)
    points = sorted(points, key=lambda x: x[0])
    result = 0
    Counter = 0
    for i in range(0, n * 2):
        if (i > 0) & (points[i][0] > points[i - 1][0]) & (Counter > 0):
            result += (points[i][0] - points[i - 1][0])
        if points[i][1]:
            Counter -= 1
        else:
            Counter += 1
    return result


if __name__ == '__main__':
    segments = [(2, 5), (4, 8), (9, 12)]
    print(segmentUnionLength(segments))

# Expected output:
9
# find all duplicate and missing numbers in given permutation array of 1 to n | function to find the duplicate and the missing elements over the range [ 1 , n ] ; stores the missing and duplicate numbers in the array arr [ ] ; traverse the given array arr [ ] ; check if the current element is not same as the element at index arr [ i ] - 1 , then swap ; otherwise , increment the index ; traverse the array again ; if the element is not at its correct position ; stores the missing and the duplicate elements ; print the missing number ; print the duplicate number ; 
def findElements(arr, N):
    i = 0
    missing = []
    duplicate = set()
    while (i != N):
        if (arr[i] != arr[arr[i] - 1]):
            t = arr[i]
            arr[i] = arr[arr[i] - 1]
            arr[t - 1] = t
        else:
            i += 1
    for i in range(N):
        if (arr[i] != i + 1):
            missing .append(i + 1)
            duplicate .add(arr[i])
    print("Missing Numbers: ", end="")
    for it in missing:
        print(it, end=" ")
    print("DuplicateNumbers:", end="")
    for it in list(duplicate):
        print(it, end=' ')


if __name__ == "__main__":
    arr = [1, 2, 2, 2, 4, 5, 7]
    N = len(arr)
    findElements(arr, N)

# Expected output:
Missing Numbers: 3 6 DuplicateNumbers:2
# check if elements of given array can be rearranged such that ( arr [ i ] + i * k ) % n = i for all values of i in range [ 0 , n | function to check if it is possible to generate all numbers in range [ 0 , n - 1 ] using the sum of elements + in the multiset a and b mod n ; if no more pair of elements can be selected ; if the number of elements in c = n , then return true ; otherwise return false ; stores the value of final answer ; iterate through all the pairs in the given multiset a and b ; stores the set a without x ; stores the set a without y ; stores the set a without x + y % n ; recursive call ; return answer ; function to check if it is possible to rearrange array elements such that ( arr [ i ] + i * k ) % n = i ; stores the values of arr [ ] modulo n ; stores all the values of i * k modulo n ; print answer ; 
def isPossible(A, B, C, N):
    if (len(A) == 0 or len(B) == 0):
        if (len(C) == N):
            return True
        else:
            return False
    ans = False
    for x in A:
        for y in B:
            _A = A
            _A .remove(x)
            _B = B
            _B .remove(y)
            _C = C
            _C .add((x + y) % N)
            ans = (ans or isPossible(_A, _B, _C, N))
    return ans


def rearrangeArray(arr, N, K):
    A = []
    for i in range(N):
        A .append(arr[i] % N)
    A .sort()
    B = []
    for i in range(N):
        B .append((i * K) % N)
    B .sort()
    C = set()
    if isPossible(A, B, C, N):
        print("YES")
    else:
        print("NO")


arr = [1, 2, 0]
K = 5
N = len(arr)
rearrangeArray(arr, N, K)

# Expected output:
YES
# height of factor tree for a given number | python 3 program for the above approach ; function to find the height of the factor tree of the integer n ; stores the height of factor tree ; loop to iterate over values of n ; stores if there exist a factor of n or not ; loop to find the smallest factor of n ; if i is a factor of n ; increment the height ; if there are no factors of n i . e , n is prime , break loop ; return answer ; 

from math import sqrt


def factorTree(N):
    height = 0
    while (N > 1):
        flag = False
        for i in range(2, int(sqrt(N)) + 1, 1):
            if (N % i == 0):
                N = N // i
                flag = True
                break
        height += 1
        if (flag == False):
            break
    return height


if __name__ == '__main__':
    N = 48
    print(factorTree(N))

# Expected output:
5
# maximize the largest number k such that bitwise and of k till n is 0 |  ; function to find maximum value of k which makes bitwise and zero . ; finding the power less than n ; 

import math


def findMaxK(N):
    p = math .log(N) // math .log(2)
    return int(pow(2, p))


N = 5
print(findMaxK(N) - 1)

# Expected output:
3
# count of ks in the array for a given range of indices after array updates for q queries | python3 program for the above approach ; function to build the segment tree ; base case ; since the count of zero is required set leaf node as 1 ; if the value in array is not zero , store 0 in the leaf node ; find the mid ; recursive call for left subtree ; recursive call for right subtree ; parent nodes contains the count of zero in range tl to tr ; function to find the count of 0 s in range l to r ; base case ; case when no two segment are combining ; finding the mid ; when it is required to combine left subtree and right subtree to get the range l to r ; function that updates the segment tree nodes ; base case ; if array element is 0 ; if array element is not 0 ; otherwise ; find the mid ; update the tree or count which is stored in parent node ; function to solve all the queries ; when query type is 1 ; when query type is 2 ; 

a = []
seg_tree = []
query = []


def build_tree(v, tl, tr):
    global a, seg_tree, query
    if (tl != tr):
        if (a[tl] == 0):
            seg_tree[v] = 1
        else:
            seg_tree[v] = 0
    else:
        tm = int((tl + tr) / 2)
        build_tree(v * 2, tl, tm)
        build_tree(v * 2 + 1, tm + 1, tr)
        seg_tree[v] = seg_tree[v * 2] + seg_tree[v * 2 + 1]


def frequency_zero(v, tl, tr, l, r):
    global a, seg_tree, query
    if (l > r):
        return 0
    if (l == tl and r == tr):
        return seg_tree[v]
    tm = int((tl + tr) / 2)
    return frequency_zero(v * 2, tl, tm, l, min(r, tm)) + \
        frequency_zero(v * 2 + 1, tm + 1, tr, max(l, tm + 1), r)


def update(v, tl, tr, pos, new_val):
    global a, seg_tree, query
    if (tl == tr):
        if (new_val == 0):
            seg_tree[v] = 1
        else:
            seg_tree[v] = 0
    else:
        tm = int((tl + tr) / 2)
        if (pos <= tm):
            update(v * 2, tl, tm, pos, new_val)
        else:
            update(v * 2 + 1, tm + 1, tr, pos, new_val)
        seg_tree[v] = seg_tree[v * 2] + seg_tree[v * 2 + 1]


def solve(n, q):
    global a, seg_tree, query
    qu = [5, 3, 6]
    seg_tree = [0] * (4 * n + 1)
    build_tree(1, 0, n - 1)
    for i in range(len(qu)):
        print(qu[i])
    for i in range(q, q):
        if query[i - 1][0] == 1:
            l = query[i - 1][1]
            r = query[i - 1][2]
            print(frequency_zero(1, 0, n - 1, l, r))
        else:
            a[query[i - 1][1]] = query[i - 1][2]
            pos = query[i - 1][1]
            new_val = query[i - 1][2]
            update(1, 0, n - 1, pos, new_val)


a = [9, 5, 7, 6, 9, 0, 0, 0, 0, 5, 6, 7, 3, 9, 0, 7, 0, 9, 0]
Q = 5
query = [[1, 5, 14], [2, 6, 1], [1, 0, 8], [2, 13, 0], [1, 6, 18]]
N = len(a)
solve(N, Q)

# Expected output:
5
3
6
# find a number in minimum steps | python program to find a number in minimum steps ; to represent data of a node in tree ; prints level of node n ; create a queue and insert root ; do level order traversal ; remove a node from queue ; q . pop ( ) to avoid infinite loop ; check if dequeued number is same as n ; insert children of dequeued node to queue ; 

from collections import deque
InF = 99999


class number:
    def __init__(self, n, l):
        self .no = n
        self .level = l


def findnthnumber(n):
    q = deque()
    r = number(0, 1)
    q .append(r)
    while (len(q) > 0):
        temp = q .popleft()
        if (temp .no >= InF or temp .no <= -InF):
            break
        if (temp .no == n):
            print("Found number n at level", temp .level - 1)
            break
        q .append(number(temp .no + temp .level, temp .level + 1))
        q .append(number(temp .no - temp .level, temp .level + 1))


if __name__ == '__main__':
    findnthnumber(13)

# Expected output:
Found number n at level 5
# check if all 3 candy bags can be emptied by removing 2 candies from any one bag and 1 from the other two repeatedly | python code for the above approach ; if total candies are not multiple of 4 then its not possible to be left with 0 candies ; if minimum candies of three bags are less than number of operations required then the task is not possible ; 
def can_empty(a, b, c):
    if ((a + b + c) % 4 != 0):
        return False
    else:
        m = min(a, min(b, c))
        if (m < (a + b + c) // 4):
            return False
    return True


a = 4
b = 2
c = 2
print("true"if can_empty(a, b, c)else "false")
a = 3
b = 4
c = 2
print("true"if can_empty(a, b, c)else "false")

# Expected output:
true
false
# difference between maximum and minimum average of all k | function to find the difference between averages of the maximum and the minimum subarrays of length k ; stores min and max sum ; iterate through starting points ; sum up next k elements ; update max and min moving sum ; return the difference between max and min average ; 
def Avgdifference(arr, N, K):
    min = 1000000
    max = -1
    for i in range(N - K + 1):
        sum = 0
        for j in range(K):
            sum += arr[i + j]
        if (min > sum):
            min = sum
        if (max < sum):
            max = sum
    return (max - min) / K


arr = [3, 8, 9, 15]
N = len(arr)
K = 2
print(Avgdifference(arr, N, K))

# Expected output:
6.5
# find a number in minimum steps | python3 program to find a number in minimum steps ; steps sequence ; current sum ; sign of the number ; basic steps required to get sum >= required value . ; if we have reached ahead to destination . ; if the last step was an odd number , then it has following mechanism for negating a particular number and decreasing the sum to required number also note that it may require 1 more step in order to reach the sum . ; if the current time instance is even and sum is odd than it takes 2 more steps and few negations in previous elements to reach there . ; 
def find(n):
    ans = []
    Sum = 0
    i = 0
    sign = 0
    if (n >= 0):
        sign = 1
    else:
        sign = -1
    n = abs(n)
    i = 1
    while (Sum < n):
        ans .append(sign * i)
        Sum += i
        i += 1
    if (Sum > sign * n):
        if (i % 2 != 0):
            Sum -= n
            if (Sum % 2 != 0):
                ans .append(sign * i)
                Sum += i
                i += 1
            ans[int(Sum / 2) - 1] *= -1
        else:
            Sum -= n
            if (Sum % 2 != 0):
                Sum -= 1
                ans .append(sign * i)
                ans .append(sign * -1 * (i + 1))
            ans[int((sum / 2)) - 1] *= -1
    return ans


n = 20
if (n == 0):
    print("MinimumnumberofSteps:0Stepsequence:0")
else:
    a = find(n)
    print("Minimum number of Steps:", len(a))
    print("Step sequence:")
    print(*a, sep=" ")

# Expected output:
Minimum number of Steps: 7
Step sequence:
1 2 3 -4 5 6 7
# maximum range length such that a [ i ] is maximum in given range for all i from [ 1 , n ] | python 3 program for the above approach ; function to find maximum range for each i such that arr [ i ] is max in range ; vector to store the left and right index for each i such that left [ i ] > arr [ i ] and right [ i ] > arr [ i ] ; traverse the array ; while s . top ( ) . first < a [ i ] remove the top element from the stack ; modify left [ i ] ; clear the stack ; traverse the array to find right [ i ] for each i ; while s . top ( ) . first < a [ i ] remove the top element from the stack ; modify right [ i ] ; print the value range for each i ; 

import sys


def MaxRange(A, n):
    left = [0] * n
    right = [0] * n
    s = []
    s .append((sys .maxsize, -1))
    for i in range(n):
        while (s[-1][0] < A[i]):
            s .pop()
        left[i] = s[-1][1]
        s .append((A[i], i))
    while (len(s) != 0):
        s .pop()
    s .append((sys .maxsize, n))
    for i in range(n - 1, -1, -1):
        while (s[-1][0] < A[i]):
            s .pop()
        right[i] = s[-1][1]
        s .append((A[i], i))
    for i in range(n):
        print(left[i] + 1, ' ', right[i] - 1)


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

# Expected output:
0   0
0   2
2   2
# find nth smallest number having exactly 4 divisors | function to find the nth number which has exactly 4 divisors ; the divs [ ] array to store number of divisors of every element ; the vis [ ] array to check if given number is considered or not ; the cnt stores number of elements having exactly 4 divisors ; iterate while cnt less than n ; if i is a prime ; iterate in the range [ 2 * i , 1000000 ] with increment of i ; if the number j is already considered ; dividing currnum by i until currnum % i is equal to 0 ; case a single prime in its factorization ; case of two distinct primes which divides j exactly once each ; 
def nthNumber(n):
    divs = [0 for i in range(1000000)]
    vis = [0 for i in range(1000000)]
    cnt = 0
    for i in range(2, n):
        if (divs[i] == 0):
            for j in range(2 * i, 1000000):
                if (vis[j]):
                    continue
                vis[j] = 1
                currNum = j
                count = 0
                while (currNum % i == 0):
                    divs[j] += 1
                    currNum = currNum // i
                    count += 1
                if (currNum == 1 and count == 3 and divs[j] == 3):
                    cnt += 1
                elif (currNum != 1 and divs[currNum] == 0 and count == 1 and divs[j] == 1):
                    cnt += 1
                if (cnt == n):
                    return j
    return -1


N = 24
print(nthNumber(N))

# Expected output:
94
# maximum number formed from the digits of given three numbers | function to find the maximum number formed by taking the maximum digit at the same position from each number ; stores the result ; stores the position value of a digit ; stores the digit at the unit place ; stores the digit at the unit place ; stores the digit at the unit place ; update a , b and c ; stores the maximum digit ; increment ans cur * a ; update cur ; return ans ; 
def findkey(A, B, C):
    ans = 0
    cur = 1
    while (A > 0):
        a = A % 10
        b = B % 10
        c = C % 10
        A = A // 10
        B = B // 10
        C = C // 10
        m = max(a, max(c, b))
        ans += cur * m
        cur = cur * 10
    return ans


if __name__ == '__main__':
    A = 3521
    B = 2452
    C = 1352
    print(findkey(A, B, C))

# Expected output:
3552
# count of distinct gcds among all the non | python 3 program for the above approach ; function to calculate the number of distinct gcds among all non - empty subsequences of an array ; variables to store the largest element in array and the required count ; map to store whether a number is present in a ; calculate largest number in a and mapping a to mp ; iterate over all possible values of gcd ; variable to check current gcd ; iterate over all multiples of i ; if j is present in a ; calculate gcd of all encountered multiples of i ; current gcd is possible ; return answer ; 

from math import gcd


def distinctGCDs(arr, N):
    M = -1
    ans = 0
    Mp = {}
    for i in range(N):
        M = max(M, arr[i])
        Mp[arr[i]] = 1
    for i in range(1, M + 1, 1):
        currGcd = 0
        for j in range(i, M + 1, i):
            if (j in Mp):
                currGcd = gcd(currGcd, j)
                if (currGcd == i):
                    ans += 1
                    break
    return ans


if __name__ == '__main__':
    arr = [3, 11, 14, 6, 12]
    N = len(arr)
    print(distinctGCDs(arr, N))

# Expected output:
7
# compress a binary tree into an integer diagonally | python program for the above approach ; function to compress the elements in an array into an integer ; check for each bit position ; update the count of set and non - set bits ; if number of set bits exceeds the number of non - set bits , then add set bits value to ans ; function to compress a given binary tree into an integer ; declare a map ; perform inorder traversal on the binary tree ; store all nodes of the same line together as a vector ; increase the vertical distance of left child ; vertical distance remains same for right child ; store all the compressed values of diagonal elements in an array ; compress the array into an integer ; 

class TreeNode:
    def __init__(self, val='', left=None, right=None):
        self .val = val
        self .left = left
        self .right = right


def findCompressValue(arr):
    ans = 0
    getBit = 1
    for i in range(32):
        S = 0
        NS = 0
        for j in arr:
            if getBit & j:
                S += 1
            else:
                NS += 1
        if S > NS:
            ans += 2 ** i
        getBit <<= 1
    return ans


def findInteger(root):
    mp = {}

    def diagonalOrder(root, d, mp):
        if not root:
            return
        try:
            mp[d].append(root .val)
        except KeyError:
            mp[d] = [root .val]
        diagonalOrder(root .left, d + 1, mp)
        diagonalOrder(root .right, d, mp)
    diagonalOrder(root, 0, mp)
    arr = []
    for i in mp:
        arr .append(findCompressValue(mp[i]))
    return findCompressValue(arr)


root = TreeNode(6)
root .left = TreeNode(5)
root .right = TreeNode(3)
root .left .left = TreeNode(3)
root .left .right = TreeNode(5)
root .right .left = TreeNode(3)
root .right .right = TreeNode(4)
print(findInteger(root))

# Expected output:
7
# egg dropping puzzle | dp |  ; function to get minimum number of trials needed in worst case with n eggs and k floors ; if there are no floors , then no trials needed . or if there is one floor , one trial needed . ; we need k trials for one egg and k floors ; consider all droppings from 1 st floor to kth floor and return the minimum of these values plus 1. ; 

import sys


def eggDrop(n, k):
    if (k == 1 or k == 0):
        return k
    if (n == 1):
        return k
    min = sys .maxsize
    for x in range(1, k + 1):
        res = max(eggDrop(n - 1, x - 1), eggDrop(n, k - x))
        if (res < min):
            min = res
    return min + 1


if __name__ == "__main__":
    n = 2
    k = 10
    print("Minimum number of trials in worst case with",
          n, "eggs and", k, "floors is", eggDrop(n, k))

# Expected output:
Minimum number of trials in worst case with 2 eggs and 10 floors is 4