giulio98/xlcost-single-prompt huggingface dataset:
# number of pairs such that path between pairs has the two vertices a and b | python 3 program to find the number of pairs such that the path between every pair contains two given vertices ; function to perform dfs on the given graph by fixing the a vertex ; to mark a particular vertex as visited ; variable to store the count of the vertices which can be reached from a ; performing the dfs by iterating over the visited array ; if the vertex is not visited and removing the vertex b ; function to return the number of pairs such that path between any two pairs consists of the given two vertices a and b ; initializing the visited array and assigning it with 0 's ; initially , the count of vertices is 0 ; performing dfs by removing the vertex b ; count the vertices which cannot be reached after removing the vertex b ; again reinitializing the visited array ; setting the count of vertices to 0 to perform the dfs again ; performing the dfs by removing the vertex a ; count the vertices which cannot be reached after removing the vertex a ; multiplying both the vertices set ; 

N = 1000001
c = 0
n = 0
m = 0
a = 0
b = 0


def dfs(a, b, v, vis):
    global c
    vis[a] = 1
    c += 1
    for i in v[a]:
        if (vis[i] == 0 and i != b):
            dfs(i, b, v, vis)


def Calculate(v):
    global c
    vis = [0 for i in range(n + 1)]
    c = 0
    dfs(a, b, v, vis)
    ans1 = n - c - 1
    vis = [0 for i in range(len(vis))]
    c = 0
    dfs(b, a, v, vis)
    ans2 = n - c - 1
    print(ans1 * ans2)


if __name__ == '__main__':
    n = 7
    m = 7
    a = 3
    b = 5
    edges = [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 5]]
    v = [[]for i in range(n + 1)]
    for i in range(m):
        v[edges[i][0]].append(edges[i][1])
        v[edges[i][1]].append(edges[i][0])
    Calculate(v)

# Expected output:
4
# generate all the binary strings of n bits | function to print the output ; function to generate all binary strings ; first assign "0" at ith position and try for all other permutations for remaining positions ; and then assign "1" at ith position and try for all other permutations for remaining positions ; 
def printTheArray(arr, n):
    for i in range(0, n):
        print(arr[i], end=" ")
    print()


def generateAllBinaryStrings(n, arr, i):
    if i == n:
        printTheArray(arr, n)
        return
    arr[i] = 0
    generateAllBinaryStrings(n, arr, i + 1)
    arr[i] = 1
    generateAllBinaryStrings(n, arr, i + 1)


if __name__ == "__main__":
    n = 4
    arr = [None] * n
    generateAllBinaryStrings(n, arr, 0)

# Expected output:
0 0 0 0 
0 0 0 1 
0 0 1 0 
0 0 1 1 
0 1 0 0 
0 1 0 1 
0 1 1 0 
0 1 1 1 
1 0 0 0 
1 0 0 1 
1 0 1 0 
1 0 1 1 
1 1 0 0 
1 1 0 1 
1 1 1 0 
1 1 1 1
# combinations where every element appears twice and distance between appearances is equal to the value | find all combinations that satisfies given constraints ; if all elements are filled , print the solution ; try all possible combinations for element elem ; if position i and ( i + elem + 1 ) are not occupied in the vector ; place elem at position i and ( i + elem + 1 ) ; recurse for next element ; backtrack ( remove elem from position i and ( i + elem + 1 ) ) ; create a vector of double the size of given number with ; all its elements initialized by 1 ; start from element 1 ; 
def allCombinationsRec(arr, elem, n):
    if (elem > n):
        for i in (arr):
            print(i, end=" ")
        print("")
        return
    for i in range(0, 2 * n):
        if (arr[i] == -1 and (i + elem + 1) <
                2 * n and arr[i + elem + 1] == -1):
            arr[i] = elem
            arr[i + elem + 1] = elem
            allCombinationsRec(arr, elem + 1, n)
            arr[i] = -1
            arr[i + elem + 1] = -1


def allCombinations(n):
    arr = [-1] * (2 * n)
    elem = 1
    allCombinationsRec(arr, elem, n)


n = 3
allCombinations(n)

# Expected output:
3 1 2 1 3 2 
2 3 1 2 1 3
# find all distinct subsets of a given set using bitmasking approach | function to find all subsets of given set . any repeated subset is considered only once in the output ; run counter i from 000. . 0 to 111. . 1 ; consider each element in the set ; check if jth bit in the i is set . if the bit is set , we consider jth element from set ; if subset is encountered for the first time if we use set < string > , we can directly insert ; consider every subset ; split the subset and print its elements ; 
def printPowerSet(arr, n):
    _list = []
    for i in range(2 ** n):
        subset = ""
        for j in range(n):
            if (i & (1 << j)) != 0:
                subset += str(arr[j]) + "|"
        if subset not in _list and len(subset) > 0:
            _list .append(subset)
    for subset in _list:
        arr = subset .split(' ')
        for string in arr:
            print(string, end=" ")
        print()


if __name__ == '__main__':
    arr = [10, 12, 12]
    n = len(arr)
    printPowerSet(arr, n)

# Expected output:
10| 
12| 
10|12| 
12|12| 
10|12|12|
# m coloring problem | backtracking | python3 program for the above approach ; a node class which stores the color and the edges connected to the node ; create a visited array of n nodes , initialized to zero ; maxcolors used till now are 1 as all nodes are painted color 1 ; do a full bfs traversal from all unvisited starting points ; if the starting point is unvisited , mark it visited and push it in queue ; bfs travel starts here ; checking all adjacent nodes to " top " edge in our queue ; important : if the color of the adjacent node is same , increase it by 1 ; if number of colors used shoots m , return 0 ; if the adjacent node is not visited , mark it visited and push it in queue ; 

from queue import Queue


class node:
    color = 1
    edges = set()


def canPaint(nodes, n, m):
    visited = [0 for _ in range(n + 1)]
    maxColors = 1
    for _ in range(1, n + 1):
        if visited[_]:
            continue
        visited[_] = 1
        q = Queue()
        q .put(_)
        while not q .empty():
            top = q .get()
            for _ in nodes[top].edges:
                if nodes[top].color == nodes[_].color:
                    nodes[_].color += 1
                maxColors = max(
                    maxColors, max(
                        nodes[top].color, nodes[_].color))
                if maxColors > m:
                    print(maxColors)
                    return 0
                if not visited[_]:
                    visited[_] = 1
                    q .put(_)
    return 1


if __name__ == "__main__":
    n = 4
    graph = [[0, 1, 1, 1], [1, 0, 1, 0], [1, 1, 0, 1], [1, 0, 1, 0]]
    m = 3
    nodes = []
    for _ in range(n + 1):
        nodes .append(node())
    for _ in range(n):
        for __ in range(n):
            if graph[_][__]:
                nodes[_].edges .add(_)
                nodes[__].edges .add(__)
    print(canPaint(nodes, n, m))

# Expected output:
1
# fast doubling method to find the nth fibonacci number | python3 program to find the nth fibonacci number using fast doubling method ; function calculate the n - th fibanacci number using fast doubling method ; base condition ; here a = f ( n ) ; here b = f ( n + 1 ) ; as f ( 2 n ) = f ( n ) [ 2f ( n + 1 ) f ( n ) ] here c = f ( 2 n ) ; as f ( 2 n + 1 ) = f ( n ) ^ 2 + f ( n + 1 ) ^ 2 here d = f ( 2 n + 1 ) ; check if n is odd or even ; 

MOD = 1000000007


def FastDoubling(n, res):
    if (n == 0):
        res[0] = 0
        res[1] = 1
        return
    FastDoubling((n // 2), res)
    a = res[0]
    b = res[1]
    c = 2 * b - a
    if (c < 0):
        c += MOD
    c = (a * c) % MOD
    d = (a * a + b * b) % MOD
    if (n % 2 == 0):
        res[0] = c
        res[1] = d
    else:
        res[0] = d
        res[1] = c + d


N = 6
res = [0] * 2
FastDoubling(N, res)
print(res[0])

# Expected output:
8
# frequency of an integer in the given array using divide and conquer | function to return the frequency of x in the subarray arr [ low ... high ] ; if the subarray is invalid or the element is not found ; if there 's only a single element  which is equal to x ; divide the array into two parts and then find the count of occurrences of x in both the parts ; 
def count(arr, low, high, x):
    if ((low > high) or (low == high and arr[low] != x)):
        return 0
    if (low == high and arr[low] == x):
        return 1
    return count(arr, low, (low + high) // 2, x) + \
        count(arr, 1 + (low + high) // 2, high, x)


if __name__ == '__main__':
    arr = [30, 1, 42, 5, 56, 3, 56, 9]
    n = len(arr)
    x = 56
    print(count(arr, 0, n - 1, x))

# Expected output:
2
# median of an unsorted array using quick select algorithm | python3 program to find median of an array ; returns the correct position of pivot element ; picks a random pivot element between l and r and partitions arr [ l . . r ] around the randomly picked element using partition ( ) ; utility function to find median ; if l < r ; find the partition index ; if partition index = k , then we found the median of odd number element in arr [ ] ; if index = k - 1 , then we get a & b as middle element of arr [ ] ; if partitionindex >= k then find the index in first half of the arr [ ] ; if partitionindex <= k then find the index in second half of the arr [ ] ; function to find median ; if n is odd ; if n is even ; print the median of arr [ ] ; 

import random
a, b = None, None


def Partition(arr, l, r):
    lst = arr[r]
    i = l
    j = l
    while (j < r):
        if (arr[j] < lst):
            arr[i], arr[j] = arr[j], arr[i]
            i += 1
        j += 1
    arr[i], arr[r] = arr[r], arr[i]
    return i


def randomPartition(arr, l, r):
    n = r - l + 1
    pivot = random .randrange(1, 100) % n
    arr[l + pivot], arr[r] = arr[r], arr[l + pivot]
    return Partition(arr, l, r)


def MedianUtil(arr, l, r, k, a1, b1):
    global a, b
    if (l <= r):
        partitionIndex = randomPartition(arr, l, r)
        if (partitionIndex == k):
            b = arr[partitionIndex]
            if (a1 != -1):
                return
        elif (partitionIndex == k - 1):
            a = arr[partitionIndex]
            if (b1 != -1):
                return
        if (partitionIndex >= k):
            return MedianUtil(arr, l, partitionIndex - 1, k, a, b)
        else:
            return MedianUtil(arr, partitionIndex + 1, r, k, a, b)
    return


def findMedian(arr, n):
    global a
    global b
    a = -1
    b = -1
    if (n % 2 == 1):
        MedianUtil(arr, 0, n - 1, n // 2, a, b)
        ans = b
    else:
        MedianUtil(arr, 0, n - 1, n // 2, a, b)
        ans = (a + b) // 2
    print("Median = ", ans)


arr = [12, 3, 5, 7, 4, 19, 26]
n = len(arr)
findMedian(arr, n)

# Expected output:
Median =  7
# largest number n which can be reduced to 0 in k steps | utility function to return the first digit of a number . ; remove last digit from number till only one digit is left ; return the first digit ; utility function that returns the count of numbers written down when starting from n ; function to find the largest number n which can be reduced to 0 in k steps ; get the sequence length of the mid point ; until k sequence length is reached ; update mid point ; get count of the new mid point ; update right to mid ; update left to mid ; increment mid point by one while count is equal to k to get the maximum value of mid point ; 
def firstDigit(n):
    while (n >= 10):
        n //= 10
    return n


def getCount(n):
    count = 1
    while (n != 0):
        leadDigit = firstDigit(n)
        n -= leadDigit
        count += 1
    return count


def getLargestNumber(k):
    left = k
    right = k * 10
    mid = (left + right) // 2
    length = getCount(mid)
    while (length != k):
        mid = (left + right) // 2
        length = getCount(mid)
        if (length > k):
            right = mid
        else:
            left = mid
    while (length == k):
        if (length != getCount(mid + 1)):
            break
        mid += 1
    return mid


if __name__ == "__main__":
    k = 3
    print(getLargestNumber(k))

# Expected output:
10
# check if point ( x , y ) can be reached from origin ( 0 , 0 ) with jump of 1 and n perpendicularly simultaneously | function to check if ( x , y ) is reachable from ( 0 , 0 ) using the jumps of given type ; case where source & destination are the same ; check for even n ( x , y ) is reachable or not ; if n is odd and parity of x and y is different return , no valid sequence of jumps exist ; 
def checkReachability(N, X, Y):
    if (X == 0 and Y == 0):
        return "YES"
    if (N % 2 == 0):
        return "YES"
    else:
        if (X % 2 != Y % 2):
            return "NO"
        else:
            return "YES"


if __name__ == '__main__':
    N = 2
    X = 5
    Y = 4
    print(checkReachability(N, X, Y))

# Expected output:
YES
# find three vertices in an n | function to find three vertices that subtends an angle closest to a ; stores the closest angle to a ; stores the count of edge which subtend an angle of a ; iterate in the range [ 1 , n - 2 ] ; stores the angle subtended ; if absolute ( angle - a ) is less than absolute ( mi - a ) ; update angle to mi , and also update i to ans ; pr the vertices ; 

import math
import sys


def closestsAngle(N, A):
    mi = sys .maxsize
    ans = 0
    for i in range(N):
        angle = 180.0 * i / N
        if (math .fabs(angle - A) < math .fabs(mi - A)):
            mi = angle
            i += 1
            ans = i
    print(2, 1, 2 + ans)


if __name__ == '__main__':
    N = 3
    A = 15
    closestsAngle(N, A)

# Expected output:
2 1 3
# area of a triangle with two vertices at midpoints of opposite sides of a square and the other vertex lying on vertex of a square | python3 program for the above approach ; function to find the area of the triangle that inscribed in square ; stores the length of the first side of triangle ; stores the length of the second side of triangle ; stores the length of the third side of triangle ; stores the area of the triangle ; return the resultant area ; 

from math import sqrt


def areaOftriangle(side):
    a = sqrt(pow(side / 2, 2) + pow(side / 2, 2))
    b = sqrt(pow(side, 2) + pow(side / 2, 2))
    c = sqrt(pow(side, 2) + pow(side / 2, 2))
    s = (a + b + c) / 2
    area = sqrt(s * (s - a) * (s - b) * (s - c))
    return round(area, 1)


if __name__ == '__main__':
    N = 10
    print(areaOftriangle(N))

# Expected output:
37.5
# equation of a straight line with perpendicular distance d from origin and an angle a between the perpendicular from origin and x | python3 program for the approach ; function to find equation of a line whose distance from origin and angle made by the perpendicular from origin with x - axis is given ; convert angle from degree to radian ; handle the special case ; calculate the sin and cos of angle ; print the equation of the line ; 

import math


def findLine(distance, degree):
    x = degree * 3.14159 / 180
    if (degree > 90):
        print("Not Possible")
        return
    result_1 = math.sin(x)
    result_2 = math.cos(x)
    print('%.2f' % result_2,
          "x +", '%.2f' % result_1,
          "y = ", distance, sep="")


D = 10
A = 30
findLine(D, A)

# Expected output:
0.87x +0.50y = 10
# count number of coordinates from an array satisfying the given conditions | function to count the number of coordinates from a given set that satisfies the given conditions ; stores the count of central points ; find all possible pairs ; initialize variables c1 , c2 , c3 , c4 to define the status of conditions ; stores value of each point ; check the conditions for each point by generating all possible pairs ; if arr [ j ] [ 0 ] > x and arr [ j ] [ 1 ] == y ; if arr [ j ] [ 0 ] < x and arr [ j ] [ 1 ] = = y ; if arr [ j ] [ 1 ] > y and arr [ j ] [ 0 ] == x ; if arr [ j ] [ 1 ] < y and arr [ j ] [ 0 ] = = x ; if all conditions satisfy then point is central point ; increment the count by 1 ; return the count ; 
def centralPoints(arr, N):
    count = 0
    for i in range(N):
        c1 = 0
        c2 = 0
        c3 = 0
        c4 = 0
        x = arr[i][0]
        y = arr[i][1]
        for j in range(N):
            if (arr[j][0] > x and arr[j][1] == y):
                c1 = 1
            if (arr[j][1] > y and arr[j][0] == x):
                c2 = 1
            if (arr[j][0] < x and arr[j][1] == y):
                c3 = 1
            if (arr[j][1] < y and arr[j][0] == x):
                c4 = 1
        if (c1 + c2 + c3 + c4 == 4):
            count += 1
    return count


if __name__ == '__main__':
    arr = [[1, 0], [2, 0], [1, 1], [1, -1]]
    N = len(arr)
    print(centralPoints(arr, N))

# Expected output:
0
# displacement from origin after n moves of given distances in specified directions | python3 program for the above approach ; function to find the displacement from the origin and direction after performing the given set of moves ; stores the distances travelled in the directions north , south , east , and west respectively ; store the initial position of robot ; traverse the array b [ ] ; if the current direction is north ; if the current direction is south ; if the current direction is east ; if the current direction is west ; stores the total vertical displacement ; stores the total horizontal displacement ; find the displacement ; print the displacement and direction after n moves ; 

from math import sqrt, floor


def finalPosition(a, b, M):
    n = 0
    s = 0
    e = 0
    w = 0
    p = 'N'
    for i in range(M):
        if (p == 'N'):
            if (a[i] == 'U'):
                p = 'N'
                n = n + b[i]
            elif (a[i] == 'D'):
                p = 'S'
                s = s + b[i]
            elif (a[i] == 'R'):
                p = 'E'
                e = e + b[i]
            elif (a[i] == 'L'):
                p = 'W'
                w = w + b[i]
        elif (p == 'S'):
            if (a[i] == 'U'):
                p = 'S'
                s = s + b[i]
            elif (a[i] == 'D'):
                p = 'N'
                n = n + b[i]
            elif (a[i] == 'R'):
                p = 'W'
                w = w + b[i]
            elif (a[i] == 'L'):
                p = 'E'
                e = e + b[i]
        elif (p == 'E'):
            if (a[i] == 'U'):
                p = 'E'
                e = e + b[i]
            elif (a[i] == 'D'):
                p = 'W'
                w = w + b[i]
            elif (a[i] == 'R'):
                p = 'S'
                s = s + b[i]
            elif (a[i] == 'L'):
                p = 'N'
                n = n + b[i]
        elif (p == 'W'):
            if (a[i] == 'U'):
                p = 'W'
                w = w + b[i]
            elif (a[i] == 'D'):
                p = 'E'
                e = e + b[i]
            elif (a[i] == 'R'):
                p = 'N'
                n = n + b[i]
            elif (a[i] == 'L'):
                p = 'S'
                s = s + b[i]
    ver_disp = n - s
    hor_disp = e - w
    displacement = floor(
        sqrt((ver_disp * ver_disp) + (hor_disp * hor_disp)) + 1)
    print(displacement, p)


if __name__ == '__main__':
    A = ['U', 'R', 'R', 'R', 'R']
    B = [1, 1, 1, 1, 0]
    N = len(A)
    finalPosition(A, B, N)

# Expected output:
1 N
# program to find length of latus rectum of an ellipse | function to calculate the length of the latus rectum of an ellipse ; length of major axis ; length of minor axis ; length of the latus rectum ; 
def lengthOfLatusRectum(A, B):
    major = 2.0 * A
    minor = 2.0 * B
    latus_rectum = (minor * minor) / major
    return latus_rectum


if __name__ == "__main__":
    A = 3.0
    B = 2.0
    print('%.5f' % lengthOfLatusRectum(A, B))

# Expected output:
2.66667
# program to find the length of latus rectum of a parabola | python 3 program for the above approach ; function to calculate distance between two points ; calculating distance ; function to calculate length of the latus rectum of a parabola ; stores the co - ordinates of the vertex of the parabola ; stores the co - ordinates of the focus of parabola ; print the distance between focus and vertex ; 

from math import sqrt


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


def lengthOfLatusRectum(a, b, c):
    vertex = [(-b / (2 * a)), (((4 * a * c) - (b * b)) / (4 * a))]
    focus = [(-b / (2 * a)), (((4 * a * c) - (b * b) + 1) / (4 * a))]
    print(
        "{:.6f}".format(
            4 *
            distance(
                focus[0],
                focus[1],
                vertex[0],
                vertex[1])))


if __name__ == "__main__":
    a = 3
    b = 5
    c = 1
    lengthOfLatusRectum(a, b, c)

# Expected output:
0.333333
# program to convert polar co | python 3 program for the above approach ; function to convert degree to radian ; function to convert the polar coordinate to cartesian ; convert degerees to radian ; applying the formula : x = rcos ( theata ) , y = rsin ( theta ) ; print cartesian coordinates ; 

import math


def ConvertDegToRad(degree):
    pi = 3.14159
    return (degree * (pi / 180.0))


def ConvertToCartesian(polar):
    polar[1] = ConvertDegToRad(polar[1])
    cartesian = [
        polar[0] *
        math .cos(
            polar[1]),
        polar[0] *
        math .sin(
            polar[1])]
    print('%.3f' % cartesian[0], '%.3f' % cartesian[1])


if __name__ == "__main__":
    polar = [1.4142, 45]
    ConvertToCartesian(polar)

# Expected output:
1.000 1.000
# distance between orthocenter and circumcenter of a right | python3 program for the above approach ; function to calculate euclidean distance between the points p1 and p2 ; stores x coordinates of both points ; stores y coordinates of both points ; return the euclid distance using distance formula ; function to find orthocenter of the right angled triangle ; find the length of the three sides ; orthocenter will be the vertex opposite to the largest side ; function to find the circumcenter of right angle triangle ; circumcenter will be located at center of hypotenuse ; if ab is the hypotenuse ; if bc is the hypotenuse ; if ac is the hypotenuse ; function to find distance between orthocenter and circumcenter ; find circumcenter ; find orthocenter ; find the distance between the orthocenter and circumcenter ; print distance between orthocenter and circumcenter ; 

import math


def distance(p1, p2):
    x1, x2 = p1[0], p2[0]
    y1, y2 = p1[1], p2[1]
    return int(math .sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2)))


def find_orthocenter(A, B, C):
    AB = distance(A, B)
    BC = distance(B, C)
    CA = distance(C, A)
    if (AB > BC and AB > CA):
        return C
    if (BC > AB and BC > CA):
        return A
    return B


def find_circumcenter(A, B, C):
    AB = distance(A, B)
    BC = distance(B, C)
    CA = distance(C, A)
    if (AB > BC and AB > CA):
        return ((A[0] + B[0]) // 2, (A[1] + B[1]) // 2)
    if (BC > AB and BC > CA):
        return ((B[0] + C[0]) // 2, (B[1] + C[1]) // 2)
    return ((C[0] + A[0]) // 2, (C[1] + A[1]) // 2)


def findDistance(A, B, C):
    circumcenter = find_circumcenter(A, B, C)
    orthocenter = find_orthocenter(A, B, C)
    distance_between = distance(circumcenter, orthocenter)
    print(distance_between)


A = [0, 0]
B = [6, 0]
C = [0, 8]
findDistance(A, B, C)

# Expected output:
5