giulio98/xlcost-single-prompt huggingface dataset:
# find all angles of a given triangle | python3 code to find all three angles of a triangle given coordinate of all three vertices ; returns square of distance b / w two points ; square of lengths be a2 , b2 , c2 ; length of sides be a , b , c ; from cosine law ; converting to degree ; printing all the angles ; 

import math


def lengthSquare(X, Y):
    xDiff = X[0] - Y[0]
    yDiff = X[1] - Y[1]
    return xDiff * xDiff + yDiff * yDiff


def printAngle(A, B, C):
    a2 = lengthSquare(B, C)
    b2 = lengthSquare(A, C)
    c2 = lengthSquare(A, B)
    a = math .sqrt(a2)
    b = math .sqrt(b2)
    c = math .sqrt(c2)
    alpha = math .acos((b2 + c2 - a2) / (2 * b * c))
    betta = math .acos((a2 + c2 - b2) / (2 * a * c))
    gamma = math .acos((a2 + b2 - c2) / (2 * a * b))
    alpha = alpha * 180 / math .pi
    betta = betta * 180 / math .pi
    gamma = gamma * 180 / math .pi
    print("alpha : %f" % (alpha))
    print("betta : %f" % (betta))
    print("gamma : %f" % (gamma))


A = (0, 0)
B = (0, 1)
C = (1, 0)
printAngle(A, B, C)

# Expected output:
alpha : 90.000000
betta : 45.000000
gamma : 45.000000
# triangle with no point inside | python3 program to find triangle with no point inside ; method to get square of distance between ( x1 , y1 ) and ( x2 , y2 ) ; method prints points which make triangle with no point inside ; any point can be chosen as first point of triangle ; choose nearest point as second point of triangle ; get distance from first point and choose nearest one ; pick third point by finding the second closest point with different slope . ; if already chosen point then skip them ; get distance from first point ; here cross multiplication is compared instead of division comparison ; 

import sys


def getDistance(x1, y1, x2, y2):
    return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)


def triangleWithNoPointInside(points, N):
    first = 0
    second = 0
    third = 0
    minD = sys .maxsize
    for i in range(0, N):
        if i == first:
            continue
        d = getDistance(
            points[i][0],
            points[i][1],
            points[first][0],
            points[first][1])
        if minD > d:
            minD = d
            second = i
    minD = sys .maxsize
    for i in range(0, N):
        if i == first or i == second:
            continue
        d = getDistance(
            points[i][0],
            points[i][1],
            points[first][0],
            points[first][1])
        if ((points[i][0] -
             points[first][0]) *
            (points[second][1] -
             points[first][1]) != (points[second][0] -
                                   points[first][0]) *
            (points[i][1] -
             points[first][1]) and minD > d):
            minD = d
            third = i
    print(points[first][0], ', ', points[first][1])
    print(points[second][0], ', ', points[second][1])
    print(points[third][0], ', ', points[third][1])


points = [[0, 0], [0, 2], [2, 0], [2, 2], [1, 1]]
N = len(points)
triangleWithNoPointInside(points, N)

# Expected output:
0 ,  0
1 ,  1
0 ,  2
# find the size of largest subset with positive bitwise and | function to find the largest possible subset having bitwise and positive ; stores the number of set bits at each bit position ; traverse the given array arr [ ] ; current bit position ; loop till array element becomes zero ; if the last bit is set ; increment frequency ; divide array element by 2 ; decrease the bit position ; size of the largest possible subset ; 
def largestSubset(a, N):
    bit = [0 for i in range(32)]
    for i in range(N):
        x = 31
        while (a[i] > 0):
            if (a[i] & 1 == 1):
                bit[x] += 1
            a[i] = a[i] >> 1
            x -= 1
    print(max(bit))


if __name__ == '__main__':
    arr = [7, 13, 8, 2, 3]
    N = len(arr)
    largestSubset(arr, N)

# Expected output:
3
# maximum element in connected component of given node for q queries | function to perform the find operation to find the parent of a disjoint set ; function to perform union operation of disjoint set union ; if the rank are the same ; update the maximum value ; function to find the maximum element of the set which belongs to the element queries [ i ] ; stores the parent elements of the sets ; stores the rank of the sets ; stores the maxvalue of the sets ; update parent [ i ] and maxvalue [ i ] to i ; add arr [ i ] . first and arr [ i ] . second elements to the same set ; find the parent element of the element queries [ i ] ; print the maximum value of the set which belongs to the element p ; 
def Find(parent, a):
    if (parent[parent[a]] != parent[a]):
        parent[a] = findParent(parent, parent[a])
    return parent[a]


def Union(parent, rank, maxValue, a, b):
    a = Find(parent, a)
    b = Find(parent, b)
    if (a == b):
        return
    if (rank[a] == rank[b]):
        rank[a] += 1
    if (rank[a] < rank[b]):
        temp = a
        a = b
        b = temp
    parent[b] = a
    maxValue[a] = max(maxValue[a], maxValue[b])


def findMaxValueOfSet(arr, queries, R, N, M):
    parent = [1 for i in range(R + 1)]
    rank = [0 for i in range(R + 1)]
    maxValue = [0 for i in range(R + 1)]
    for i in range(1, R + 1, 1):
        parent[i] = maxValue[i] = i
    for i in range(N):
        Union(parent, rank, maxValue, arr[i][0], arr[i][1])
    for i in range(M):
        P = Find(parent, queries[i])
        print(maxValue[P], end=" ")


if __name__ == '__main__':
    R = 5
    arr = [[1, 2], [2, 3], [4, 5]]
    queries = [2, 4, 1, 3]
    N = len(arr)
    M = len(queries)
    findMaxValueOfSet(arr, queries, R, N, M)

# Expected output:
3 5 3 3
# maximum sum of segments among all segments formed in array after q queries | python 3 program for the above approach ; stores the maximum integer of the sets for each query ; function to perform the find operation of disjoint set union ; function to perform the union operation of disjoint set union ; find the parent of a and b ; update the parent ; update the sum of set a ; function to find the maximum element from the sets after each operation ; stores the rank of the sets ; stores the sum of the sets ; stores the maximum element for each query ; initially set is empty ; update the sum as the current element ; after the last query set will be empty and sum will be 0 ; check if the current element is not in any set then make parent as current element of the queries ; check left side of the queries [ i ] is not added in any set ; add the queries [ i ] and the queries [ i ] - 1 in one set ; check right side of the queries [ i ] is not added in any set ; add queries [ i ] and the queries [ i ] + 1 in one set ; update the maxans ; push maxans to the currmax ; print currmax values in the reverse order ; 

import sys
maxAns = -sys .maxsize - 1


def Find(parent, a):
    if (parent[a] == a):
        return a
    return Find(parent, parent[a])


def Union(parent, rank, setSum, a, b):
    a = Find(parent, a)
    b = Find(parent, b)
    if (a == b):
        return
    if (rank[a] > rank[b]):
        rank[a] += 1
    if (rank[b] > rank[a]):
        swap(a, b)
    parent[b] = a
    setSum[a] += setSum[b]


def maxValues(arr, queries, N):
    global maxAns
    parent = [0]*(N + 1)
    rank = [0] * (N + 1)
    setSum = [0] * (N + 1)
    currMax = []
    for i in range(1, N + 1):
        parent[i] = -1
        setSum[i] = arr[i - 1]
    currMax .append(0)
    for i in range(N - 1, 0, -1):
        if (parent[queries[i]] == -1):
            parent[queries[i]] = queries[i]
        if (queries[i] - 1 >= 0 and parent[queries[i] - 1] != -1):
            Union(parent, rank, setSum, queries[i], queries[i] - 1)
        if (queries[i] + 1 <= N and parent[queries[i] + 1] != -1):
            Union(parent, rank, setSum, queries[i], queries[i] + 1)
        maxAns = max(setSum[queries[i]], maxAns)
        currMax .append(maxAns)
    for i in range(len(currMax) - 1, -1, -1):
        print(currMax[i], end=" ")


if __name__ == "__main__":
    arr = [1, 3, 2, 5]
    queries = [3, 4, 1, 2]
    N = len(arr)
    maxValues(arr, queries, N)

# Expected output:
5 4 3 0
# minimum length paths between 1 to n including each node | function to calculate the distances from node 1 to n ; vector to store our edges ; storing the edgees in the vector ; initialize queue ; bfs from first node using queue ; pop from queue ; traversing its adjacency list ; initialize queue ; bfs from last node using queue ; pop from queue ; traversing its adjacency list ; printing the minimum distance including node i ; if not reachable ; path exists ; 
def minDisIncludingNode(n, m, edges):
    g = [[]for i in range(10005)]
    for i in range(m):
        a = edges[i][0] - 1
        b = edges[i][1] - 1
        g[a].append(b)
        g[b].append(a)
    q = []
    q .append([0, 0])
    dist = [1e9 for i in range(n)]
    dist[0] = 0
    while (len(q) > 0):
        up = q[0]
        q = q[1:]
        x = up[0]
        lev = up[1]
        if (lev > dist[x]):
            continue
        if (x == n - 1):
            continue
        for y in g[x]:
            if (dist[y] > lev + 1):
                dist[y] = lev + 1
                q .append([y, lev + 1])
    q1 = []
    q1 .append([n - 1, 0])
    dist1 = [1e9 for i in range(n)]
    dist1[n - 1] = 0
    while (len(q1) > 0):
        up = q1[0]
        q1 = q1[1:]
        x = up[0]
        lev = up[1]
        if (lev > dist1[x]):
            continue
        if (x == 0):
            continue
        for y in g[x]:
            if (dist1[y] > lev + 1):
                dist1[y] = lev + 1
                q1 .append([y, lev + 1])
    for i in range(n):
        if (dist[i] + dist1[i] > 1e9):
            print(-1, end=" ")
        else:
            print(dist[i] + dist1[i], end=" ")


if __name__ == '__main__':
    n = 5
    m = 7
    edges = [[1, 2], [1, 4], [2, 3], [2, 5], [4, 3], [4, 5], [1, 5]]
    minDisIncludingNode(n, m, edges)

# Expected output:
1 2 4 2 1
# check if possible to make array sum equal to array product by replacing exactly one element | function to check if it is possible to form an array whose sum and the product is the same or not ; find the sum of the array ;  ; find the product of the array ; check a complete integer y for every x ; if got such y ; if no such y exist ; 
def canPossibleReplacement(N, arr):
    S = sum(arr)
    P = 1
    for i in arr:
        P *= i
    for x in arr:
        y = (S - x) // (P / x - 1)
        if (S - x + y) == (P * y)/x:
            return 'Yes'
    return 'No'


N, arr = 3, [1, 3, 4]
print(canPossibleReplacement(N, arr))

# Expected output:
Yes
# check if all the digits of the given number are same | python3 program for the above approach ; function to check if all the digits in the number n is the same or not ; get the length of n ; form the number m of the type k * 111. . . where k is the rightmost digit of n ; check if the numbers are equal ; otherwise ; 

import math


def checkSameDigits(N):
    length = int(math .log10(N)) + 1
    M = (int(math .pow(10, length)) - 1) // (10 - 1)
    M *= N % 10
    if (M == N):
        return "Yes"
    return "No"


if __name__ == "__main__":
    N = 222
    print(checkSameDigits(N))

# Expected output:
Yes
# count of even sum triplets in the array for q range queries | function to count number of triplets with even sum in range l , r for each query ; initialization of array ; initialization of variables ; traversing array ; if element is odd ; if element is even ; storing count of even and odd till each i ; traversing each query ; count of odd numbers in l to r ; count of even numbers in l to r ; finding the ans ; printing the ans ; 
def countTriplets(size, queries, arr, Q):
    arr_even = [0 for i in range(size + 1)]
    arr_odd = [0 for i in range(size + 1)]
    even = 0
    odd = 0
    arr_even[0] = 0
    arr_odd[0] = 0
    for i in range(size):
        if (arr[i] % 2):
            odd += 1
        else:
            even += 1
        arr_even[i + 1] = even
        arr_odd[i + 1] = odd
    for i in range(queries):
        l = Q[i][0]
        r = Q[i][1]
        odd = arr_odd[r] - arr_odd[l - 1]
        even = arr_even[r] - arr_even[l - 1]
        ans = (even * (even - 1) * (even - 2)) // 6 + \
            (odd * (odd - 1) // 2) * even
        print(ans, end=" ")


if __name__ == '__main__':
    N = 6
    Q = 2
    arr = [1, 2, 3, 4, 5, 6]
    queries = [[1, 3], [2, 5]]
    countTriplets(N, Q, arr, queries)

# Expected output:
1 2
# maximize the rightmost element of an array in k operations in linear time | function to calculate maximum value of rightmost element ; calculating maximum value of rightmost element ; checking if arr [ i ] is operationable ; performing operation of i - th element ; decreasing the value of k by 1 ; printing rightmost element ; 
def maxRightmostElement(N, k, p, arr):
    while (k):
        for i in range(N - 2, -1, -1):
            if (arr[i] >= p):
                arr[i] = arr[i] - p
                arr[i + 1] = arr[i + 1] + p
                break
        k = k - 1
    print(arr[N - 1])


N = 4
p = 2
k = 5
arr = [3, 8, 1, 4]
maxRightmostElement(N, k, p, arr)

# Expected output:
8
# mean of minimum of all possible k | function to find the value of ncr ; base case ; find ncr recursively ; function to find the expected minimum values of all the subsets of size k ; find the factorials that will be used later ; find the factorials ; total number of subsets ; stores the sum of minimum over all possible subsets ; iterate over all possible minimum ; find the mean over all subsets ; 
def nCr(n, r, f):
    if (n < r):
        return 0
    return f[n] / (f[r] * f[n - r])


def findMean(N, X):
    f = [0 for i in range(N + 1)]
    f[0] = 1
    for i in range(1, N + 1, 1):
        f[i] = f[i - 1] * i
    total = nCr(N, X, f)
    count = 0
    for i in range(1, N + 1, 1):
        count += nCr(N - i, X - 1, f) * i
    E_X = (count) / (total)
    print("{0:.9f}".format(E_X))
    return 0


if __name__ == '__main__':
    N = 3
    X = 2
    findMean(N, X)

# Expected output:
1.333333333
# maximize count of odd | to find maximum number of pairs in array with conversion of at most one element ; initialize count of even elements ; initialize count of odd elements ; if current number is even then increment x by 1 ; if current number is odd then increment y by 1 ; initialize the answer by min ( x , y ) ; if difference in count of odd and even is more than 2 than increment answer ; return final answer ; 
def maximumNumberofpairs(n, arr):
    x = 0
    y = 0
    for i in range(n):
        if (arr[i] % 2 == 0):
            x += 1
        else:
            y += 1
    answer = min(x, y)
    if (abs(x - y) >= 2):
        answer += 1
    return answer


if __name__ == '__main__':
    arr = [1, 2, 4, 6, 5, 10, 12]
    n = len(arr)
    print(maximumNumberofpairs(n, arr))

# Expected output:
3
# sum of product of all unordered pairs in given range with update queries | function to calculate the pairwise product sum in range from l to r ; loop to iterate over all possible pairs from l to r ; print answer ; function to update the array element at index p to x ; update the value at pth index in the array ; function to solve q queries ; if query is of type 1 ; if query is of type 2 ; 
def pairwiseProductSum(a, l, r):
    sum = 0
    for j in range(l - 1, r, 1):
        for k in range(j + 1, r, 1):
            sum += (a[j] * a[k])
    print(sum)


def updateArray(a, p, x):
    a[p - 1] = x


def solveQueries(a, n, Q, query):
    for i in range(Q):
        if (query[i][0] == 1):
            pairwiseProductSum(a, query[i][1], query[i][2])
        else:
            updateArray(a, query[i][1], query[i][2])


if __name__ == '__main__':
    A = [5, 7, 2, 3, 1]
    N = len(A)
    Q = 3
    query = [[1, 1, 3], [2, 2, 5], [1, 2, 5]]
    solveQueries(A, N, Q, query)

# Expected output:
59
41
# check if final remainder is present in original array by reducing it based on 
def Reduced(a, n):
    original_array = a[:]
    while len(a) != 2:
        mid = len(a) // 2
        mid_ele = a[mid]
        start = a .pop(0)
        end = a .pop()
        rmd = (start * end) % mid_ele
        a .append(rmd)
    remainder = (a[0] * a[1]) % n
    if remainder in original_array:
        return 1
    return 0


Arr = [2, 3, 4, 8, 5, 7]
N = len(Arr)
x = Reduced(Arr, N)
if x:
    print("YES")
else:
    print("NO")

# Expected output:
YES
# find two numbers from their sum and or | python 3 program for the above approach ; function to find the two integers from the given sum and bitwise or value ; check if z is non negative ; iterate through all the bits ; find the kth bit of a & b ; find the kth bit of a | b ; if bit1 = 1 and bit2 = 0 , then there will be no possible pairs ; print the possible pairs ; 

MaxBit = 32


def possiblePair(X, Y):
    Z = Y - X
    if (Z < 0):
        print("-1")
        return 0
    for k in range(MaxBit):
        bit1 = (Z >> k) & 1
        bit2 = (Z >> k) & 1
        if (bit1 == 1 and bit2 == 0):
            print("-1")
            return 0
    print(Z, X)
    return 0


if __name__ == '__main__':
    X = 7
    Y = 11
    possiblePair(X, Y)

# Expected output:
4 7
# maximum frequencies in each m | function to find the frequency of the most common element in each m length subarrays ; stores frequency of array element ; stores the maximum frequency ; iterate for the first sub - array and store the maximum ; print the maximum frequency for the first subarray ; iterate over the range [ m , n ] ; subtract the a [ i - m ] and add the a [ i ] in the map ; find the maximum frequency ; print the maximum frequency for the current subarray ; 
def maxFrequencySubarrayUtil(A, N, M):
    i = 0
    m = {}
    val = 0
    while (i < M):
        if A[i] in m:
            m[A[i]] += 1
        else:
            m[A[i]] = 1
        val = max(val, m[A[i]])
        i += 1
    print(val, end=" ")
    for i in range(M, N, 1):
        if A[i - M] in m:
            m[A[i - M]] -= 1
        else:
            m[A[i - M]] = 0
        if A[i] in m:
            m[A[i]] += 1
        val = 0
        for key, value in m .items():
            val = max(val, value)
        print(val, end=" ")


if __name__ == '__main__':
    A = [1, 1, 2, 2, 3, 5]
    N = len(A)
    M = 4
    maxFrequencySubarrayUtil(A, N, M)

# Expected output:
2 2 2
# maximum number of pairs of distinct array elements possible by including each element in only one pair | function to count the maximum number of pairs having different element from the given array ; stores the frequency of array element ; stores maximum count of pairs ; increasing the frequency of every element ; stores the frequencies of array element from highest to lowest ; pushing the frequencies to the priority queue ; iterate until size of pq > 1 ; stores the top two element ; form the pair between the top two pairs ; decrement the frequencies ; insert updated frequencies if it is greater than 0 ; return the total count of resultant pairs ; 
def maximumPairs(a, n):
    freq = {}
    count = 0
    for i in range(n):
        if a[i] in freq:
            freq[a[i]] += 1
        else:
            freq[a[i]] = 1
    pq = []
    for key, value in freq .items():
        pq .append(value)
    pq .sort()
    while (len(pq) > 1):
        freq1 = pq[len(pq) - 1]
        pq = pq[:-1]
        freq2 = pq[len(pq) - 1]
        pq = pq[:-1]
        count += 1
        freq1 -= 1
        freq2 -= 1
        if (freq1 > 0):
            pq .append(freq1)
        if (freq2 > 0):
            pq .append(freq2)
        pq .sort()
    return count


if __name__ == '__main__':
    arr = [4, 2, 4, 1, 4, 3]
    N = len(arr)
    print(maximumPairs(arr, N))

# Expected output:
3
# generate an n | python3 program for above approach ; function to print target array ; sort the given array ; seeking for index of elements with minimum diff . ; seeking for index ; to store target array ; copying element ; copying remaining element ; printing target array ; 

import sys


def printArr(arr, n):
    arr .sort()
    minDifference = sys .maxsize
    minIndex = -1
    for i in range(1, n, 1):
        if (minDifference > abs(arr[i] - arr[i - 1])):
            minDifference = abs(arr[i] - arr[i - 1])
            minIndex = i - 1
    Arr = [0 for i in range(n)]
    Arr[0] = arr[minIndex]
    Arr[n - 1] = arr[minIndex + 1]
    pos = 1
    for i in range(minIndex + 2, n, 1):
        Arr[pos] = arr[i]
        pos += 1
    for i in range(minIndex):
        Arr[pos] = arr[i]
        pos += 1
    for i in range(n):
        print(Arr[i], end=" ")


if __name__ == '__main__':
    N = 8
    arr = [4, 6, 2, 6, 8, 2, 6, 4]
    printArr(arr, N)

# Expected output:
2 4 4 6 6 6 8 2
# minimize operations to convert each node of n | create adjacency list ; function to add an edges in graph ; function to perform the dfs of graph recursively from a given vertex u ; check for the condition for the flipping of node 's initial value ; traverse all the children of the current source node u ; swap foo and foo1 signifies there is change of level ; function to perform the dfsutil ( ) for all the unvisited vertices ; traverse the given set of nodes ; if the current node is unvisited ; print the number of operations ; function to count the number of flips required to change initial node values to final node value ; add the given edges ; dfs traversal ; 

N = 3
adj = []
for i in range(N + 1):
    adj .append([])
visited = []
ans = 0


def addEdges(u, v):
    global adj
    adj[u].append(v)
    adj[v].append(u)


def DFSUtil(u, foo, foo1, initial, finall):
    global visited, ans, adj
    visited[u] = True
    if ((initial[u - 1] ^ foo) ^ finall[u - 1]):
        ans += 1
        foo ^= True
    for i in range(len(adj[u])):
        if (visited[adj[u][i]] == False):
            DFSUtil(adj[u][i], foo1, foo, initial, finall)


def DFS(V, initial, finall):
    global ans, visited
    ans = 0
    visited = [False] * V
    for u in range(1, 2):
        if (visited[u] == False):
            DFSUtil(u, 0, 0, initial, finall)
    print(ans)


def countOperations(N, initial, finall, Edges):
    for i in range(N - 1):
        addEdges(Edges[i][0], Edges[i][1])
    DFS(N + 1, initial, finall)


Edges = [[1, 2], [1, 3]]
initial = [True, True, False]
finall = [False, True, True]
countOperations(N, initial, finall, Edges)

# Expected output:
2
# minimum number of moves to make m and n equal by repeatedly adding any divisor of number to itself except 1 and the number | function to find the minimum number of moves to make n and m equal . ; array to maintain the numbers included . ; pair of vertex , count ; run bfs from n ; if we reached goal ; iterate in the range ; if i is a factor of aux ; if i is less than m - aux and is not included earlier . ; if aux / i is less than m - aux and is not included earlier . ; not possible ; 
def countOperations(N, M):
    visited = [False] * (100001)
    Q = []
    Q .append([N, 0])
    visited[N] = True
    while (len(Q) > 0):
        aux = Q[0][0]
        cont = Q[0][1]
        Q .pop(0)
        if (aux == M):
            return cont
        i = 2
        while i * i <= aux:
            if (aux % i == 0):
                if (aux + i <= M and not visited[aux + i]):
                    Q .append([aux + i, cont + 1])
                    visited[aux + i] = True
                if (aux + int(aux / i) <=
                        M and not visited[aux + int(aux / i)]):
                    Q .append([aux + int(aux / i), cont + 1])
                    visited[aux + int(aux / i)] = True
            i += 1
    return -1


N, M = 4, 24
print(countOperations(N, M))

# Expected output:
5