giulio98/xlcost-single-prompt huggingface dataset:
# check if a given string can be converted to another by given possible swaps | python3 program to implement the above approach ; stores length of str1 ; stores length of str2 ; stores distinct characters of str1 ; stores distinct characters of str2 ; stores frequency of each character of str1 ; traverse the string str1 ; update frequency of str1 [ i ] ; traverse the string str1 ; insert str1 [ i ] into st1 ; traverse the string str2 ; insert str1 [ i ] into st1 ; if distinct characters in str1 and str2 are not same ; stores frequency of each character of str2 ; traverse the string str2 ; update frequency of str2 [ i ] ; sort hash1 [ ] array ; sort hash2 [ ] array ; traverse hash1 [ ] and hash2 [ ] ; if hash1 [ i ] not equal to hash2 [ i ] ; 
def checkStr1CanConStr2(str1, str2):
    N = len(str1)
    M = len(str2)
    st1 = set([])
    st2 = set([])
    hash1 = [0] * 256
    for i in range(N):
        hash1[ord(str1[i])] += 1
    for i in range(N):
        st1 .add(str1[i])
    for i in range(M):
        st2 .add(str2[i])
    if (st1 != st2):
        return False
    hash2 = [0] * 256
    for i in range(M):
        hash2[ord(str2[i])] += 1
    hash1 .sort()
    hash2 .sort()
    for i in range(256):
        if (hash1[i] != hash2[i]):
            return False
    return True


if __name__ == "__main__":
    str1 = "xyyzzlll"
    str2 = "yllzzxxx"
    if (checkStr1CanConStr2(str1, str2)):
        print("True")
    else:
        print("False")

# Expected output:
True
# sort the array in a given index range | function to sort the elements of the array from index a to index b ; variables to store start and end of the index range ; print the modified array ; 
def partSort(arr, N, a, b):
    l = min(a, b)
    r = max(a, b)
    arr = (arr[0:l] + sorted(arr[l:r + 1]) + arr[r:N])
    for i in range(0, N, 1):
        print(arr[i], end=" ")


if __name__ == '__main__':
    arr = [7, 8, 4, 5, 2]
    a = 1
    b = 4
    N = len(arr)
    partSort(arr, N, a, b)

# Expected output:
7 2 4 5 8
# find the minimum cost to reach destination using a train | a dynamic programming based solution to find min cost to reach station n - 1 from station 0. ; this function returns the smallest possible cost to reach station n - 1 from station 0. ; dist [ i ] stores minimum cost to reach station i from station 0. ; go through every station and check if using it as an intermediate station gives better path ; 

INF = 2147483647
N = 4


def minCost(cost):
    dist = [0 for i in range(N)]
    for i in range(N):
        dist[i] = INF
    dist[0] = 0
    for i in range(N):
        for j in range(i + 1, N):
            if (dist[j] > dist[i] + cost[i][j]):
                dist[j] = dist[i] + cost[i][j]
    return dist[N - 1]


cost = [[0, 15, 80, 90], [INF, 0, 40, 50],
        [INF, INF, 0, 70], [INF, INF, INF, 0]]
print("The Minimum cost to reach station ", N, " is ", minCost(cost))

# Expected output:
The Minimum cost to reach station  4  is  65
# number of loops of size k starting from a specific node | return the number of ways from a node to make a loop of size k in undirected complete connected graph of n nodes ; 
def numOfways(n, k):
    p = 1
    if (k % 2):
        p = -1
    return (pow(n - 1, k) + p * (n - 1)) / n


n = 4
k = 2
print(numOfways(n, k))

# Expected output:
3.0
# make largest palindrome by changing at most k | returns maximum possible palindrome using k changes ; initialize l and r by leftmost and rightmost ends ; first try to make palindrome ; replace left and right character by maximum of both ; if k is negative then we can 't make  palindrome ; at mid character , if k > 0 then change it to 9 ; if character at lth ( same as rth ) is less than 9 ; if none of them is changed in the previous loop then subtract 2 from k and convert both to 9 ; if one of them is changed in the previous loop then subtract 1 from k ( 1 more is subtracted already ) and make them 9 ; 
def maximumPalinUsingKChanges(strr, k):
    palin = strr[::]
    l = 0
    r = len(strr) - 1
    while (l <= r):
        if (strr[l] != strr[r]):
            palin[l] = palin[r] = max(strr[l], strr[r])
            k -= 1
        l += 1
        r -= 1
    if (k < 0):
        return "Not possible"
    l = 0
    r = len(strr) - 1
    while (l <= r):
        if (l == r):
            if (k > 0):
                palin[l] = '9'
        if (palin[l] < '9'):
            if (k >= 2 and palin[l] == strr[l] and palin[r] == strr[r]):
                k -= 2
                palin[l] = palin[r] = '9'
            elif (k >= 1 and (palin[l] != strr[l] or palin[r] != strr[r])):
                k -= 1
                palin[l] = palin[r] = '9'
        l += 1
        r -= 1
    return palin


st = "43435"
strr = [i for i in st]
k = 3
a = maximumPalinUsingKChanges(strr, k)
print("".join(a))

# Expected output:
93939
# minimize the count of adjacent pairs with different parity | python3 implementation of above approach ; recursive function to calculate minimum adjacent pairs with different parity ; if all the numbers are placed ; if replacement is not required ; if replacement is required ; backtracking ; backtracking ; function to display the minimum number of adjacent elements with different parity ; store no of even numbers not present in the array ; store no of odd numbers not present in the array ; erase exisiting numbers ; store non - exisiting even and odd numbers ; 

mn = 1000


def parity(even, odd, v, i):
    global mn
    if (i == len(v) or len(even) == 0 or len(odd) == 0):
        count = 0
        for j in range(len(v) - 1):
            if (v[j] % 2 != v[j + 1] % 2):
                count += 1
        if (count < mn):
            mn = count
        return
    if (v[i] != -1):
        parity(even, odd, v, i + 1)
    else:
        if (len(even) != 0):
            x = even[len(even) - 1]
            even .remove(even[len(even) - 1])
            v[i] = x
            parity(even, odd, v, i + 1)
            even .append(x)
        if (len(odd) != 0):
            x = odd[len(odd) - 1]
            odd .remove(odd[len(odd) - 1])
            v[i] = x
            parity(even, odd, v, i + 1)
            odd .append(x)


def mnDiffParity(v, n):
    global mn
    even = []
    odd = []
    m = {i: 0 for i in range(100)}
    for i in range(1, n + 1):
        m[i] = 1
    for i in range(len(v)):
        if (v[i] != -1):
            m .pop(v[i])
    for key in m .keys():
        if (key % 2 == 0):
            even .append(key)
        else:
            odd .append(key)
    parity(even, odd, v, 0)
    print(mn + 4)


if __name__ == '__main__':
    n = 8
    v = [2, 1, 4, -1, -1, 6, -1, 8]
    mnDiffParity(v, n)

# Expected output:
6
# find triplet such that number of nodes connecting these triplets is maximum | python3 implementation of the approach ; to store the required nodes ; parent array to retrace the nodes ; visited array to prevent dfs in direction on diameter path ; dfs function to find the startnode ; dfs function to find the endnode of diameter and maintain the parent array ; dfs function to find the end node of the longest branch to diameter ; function to find the required nodes ; to find start node of diameter ; to find end node of diameter ; x is the end node of diameter ; mark all the nodes on diameter using back tracking ; find the end node of longest branch to diameter ; 

MAX = 100005
adjacent = [[]for i in range(MAX)]
visited = [False] * MAX
startnode = endnode = thirdnode = None
maxi, N = -1, None
parent = [None] * MAX
vis = [False] * MAX


def dfs(u, count):
    visited[u] = True
    temp = 0
    global startnode, maxi
    for i in range(0, len(adjacent[u])):
        if not visited[adjacent[u][i]]:
            temp += 1
            dfs(adjacent[u][i], count + 1)
    if temp == 0:
        if maxi < count:
            maxi = count
            startnode = u


def dfs1(u, count):
    visited[u] = True
    temp = 0
    global endnode, maxi
    for i in range(0, len(adjacent[u])):
        if not visited[adjacent[u][i]]:
            temp += 1
            parent[adjacent[u][i]] = u
            dfs1(adjacent[u][i], count + 1)
    if temp == 0:
        if maxi < count:
            maxi = count
            endnode = u


def dfs2(u, count):
    visited[u] = True
    temp = 0
    global thirdnode, maxi
    for i in range(0, len(adjacent[u])):
        if (not visited[adjacent[u][i]] and not vis[adjacent[u][i]]):
            temp += 1
            dfs2(adjacent[u][i], count + 1)
    if temp == 0:
        if maxi < count:
            maxi = count
            thirdnode = u


def findNodes():
    dfs(1, 0)
    global maxi
    for i in range(0, N + 1):
        visited[i] = False
    maxi = -1
    dfs1(startnode, 0)
    for i in range(0, N + 1):
        visited[i] = False
    x = endnode
    vis[startnode] = True
    while x != startnode:
        vis[x] = True
        x = parent[x]
    maxi = -1
    for i in range(1, N + 1):
        if vis[i]:
            dfs2(i, 0)


if __name__ == "__main__":
    N = 4
    adjacent[1].append(2)
    adjacent[2].append(1)
    adjacent[1].append(3)
    adjacent[3].append(1)
    adjacent[1].append(4)
    adjacent[4].append(1)
    findNodes()
    print("({}, {}, {})".format(startnode, endnode, thirdnode))

# Expected output:
(2, 3, 4)
# percentage increase in volume of the sphere if radius is increased by a given percentage | python3 program to find percentage increase in the volume of the sphere if radius is increased by a given percentage ; 
def newvol(x):
    print("percentage increase in the", pow(x, 3) /
          10000 + 3 * x + (3 * pow(x, 2)) / 100, "%")


x = 10.0
newvol(x)

# Expected output:
percentage increase in the 33.1 %
# length of the chord of the circle whose radius and the angle subtended at the center by the chord is given | python3 program to find the length chord of the circle whose radius and the angle subtended at the centre is also given ; function to find the length of the chord ; 

import math as mt


def length_of_chord(r, x):
    print("The length of the chord",
          " of the circle is ",
          2 * r * mt .sin(x * (3.14 / 180)))


r = 4
x = 63
length_of_chord(r, x)

# Expected output:
The length of the chord  of the circle is  7.12602654729573
# area of a square inscribed in a circle which is inscribed in an equilateral triangle | python3 program to find the area of the square inscribed within the circle which in turn is inscribed in an equilateral triangle ; function to find the area of the square ; a cannot be negative ; area of the square ; 

from math import *


def area(a):
    if a < 0:
        return -1
    area = sqrt(a) / 6
    return area


if __name__ == "__main__":
    a = 10
    print(round(area(a), 6))

# Expected output:
0.527046
# length of longest rod that can fit into a cuboid | python 3 program to find the longest rod that can fit in a cuboid ; function to find the length ; temporary variable to hold the intermediate result ; length of longest rod is calculated using square root function ; 

from math import *


def longestRodInCuboid(length, breadth, height):
    temp = length * length + breadth * breadth + height * height
    result = sqrt(temp)
    return result


if __name__ == "__main__":
    length, breadth, height = 12, 9, 8
    print(longestRodInCuboid(length, breadth, height))

# Expected output:
17.0
# check whether a given point lies on or inside the rectangle | set 3 | function to check whether a given point lies inside or on the rectangle or not ; 
def LiesInsieRectangle(a, b, x, y):
    if (x - y - b <= 0 and x - y + b >= 0 and x +
            y - 2 * a + b <= 0 and x + y - b >= 0):
        return True
    return False


if __name__ == "__main__":
    a, b, x, y = 7, 2, 4, 5
    if LiesInsieRectangle(a, b, x, y):
        print("Given point lies inside" " the rectangle")
    else:
        print("Given point does not lie" " on the rectangle")

# Expected output:
Given point lies inside the rectangle
# maximize volume of cuboid with given sum of sides | return the maximum volume . ; for length ; for breadth ; for height ; calculating maximum volume . ; 
def maxvolume(s):
    maxvalue = 0
    i = 1
    for i in range(s - 1):
        j = 1
        for j in range(s):
            k = s - i - j
            maxvalue = max(maxvalue, i * j * k)
    return maxvalue


s = 8
print(maxvolume(s))

# Expected output:
18
# maximize volume of cuboid with given sum of sides | return the maximum volume . ; finding length ; finding breadth ; finding height ; 
def maxvolume(s):
    length = int(s / 3)
    s -= length
    breadth = s / 2
    height = s - breadth
    return int(length * breadth * height)


s = 8
print(maxvolume(s))

# Expected output:
18
# area of a hexagon | python3 program to find area of a hexagon ; function for calculating area of the hexagon . ; 

import math


def hexagonArea(s):
    return ((3 * math .sqrt(3) * (s * s)) / 2)


if __name__ == "__main__":
    s = 4
    print("Area:", "{0:.4f}".format(hexagonArea(s)))

# Expected output:
Area: 41.5692
# maximum number of squares that can fit in a right angle isosceles triangle | function for finding max squares ; return in o ( 1 ) with derived formula ; 
def maxSquare(b, m):
    return (b / m - 1) * (b / m) / 2


b = 10
m = 2
print(int(maxSquare(b, m)))

# Expected output:
10
# check if right triangle possible from given area and hypotenuse | python program to check existence of right triangle . ; prints three sides of a right triangle from given area and hypotenuse if triangle is possible , else prints - 1. ; descriminant of the equation ; applying the linear equation formula to find both the roots ; 

from math import sqrt


def findRightAngle(A, H):
    D = pow(H, 4) - 16 * A * A
    if D >= 0:
        root1 = (H * H + sqrt(D)) / 2
        root2 = (H * H - sqrt(D)) / 2
        a = sqrt(root1)
        b = sqrt(root2)
        if b >= a:
            print(a, b, H)
        else:
            print(b, a, H)
    else:
        print("-1")


findRightAngle(6, 5)

# Expected output:
3.0 4.0 5
# maximum number of 2 x2 squares that can be fit inside a right isosceles triangle | python3 program to count number of 2 x 2 squares in a right isosceles triangle ; removing the extra part we would always need ; since each square has base of length of 2 ; 
def numberOfSquares(base):
    base = (base - 2)
    base = base // 2
    return base * (base + 1) / 2


base = 8
print(numberOfSquares(base))

# Expected output:
6.0
# bitwise or of bitwise and of all possible non | function to find the bitwise or of bitwise and of all possible subarrays after performing the every query ; traversing each pair of the query ; stores the bitwise or ; updating the array ; find the bitwise or of new updated array ; print the ans ; 
def performQuery(arr, Q):
    for i in range(0, len(Q)):
        orr = 0
        x = Q[i][0]
        arr[x - 1] = Q[i][1]
        for j in range(0, len(arr)):
            orr = orr | arr[j]
        print(orr, end=" ")


arr = [1, 2, 3]
Q = [[1, 4], [3, 0]]
performQuery(arr, Q)

# Expected output:
7 6
# smallest length of number divisible by k formed by using d only | function to form the smallest number possible ; array to mark the remainders counted already ; iterate over the range ; if that remainder is already found , return - 1 ; 
def smallest(k, d):
    cnt = 1
    m = d % k
    v = [0 for i in range(k)]
    v[m] = 1
    while (1):
        if (m == 0):
            return cnt
        m = (((m * (10 % k)) % k) + (d % k)) % k
        if (v[m] == 1):
            return -1
        v[m] = 1
        cnt += 1
    return -1


d = 1
k = 41
print(smallest(k, d))

# Expected output:
5
# fibonacci cube graph | function to find fibonacci number ; function for finding number of vertices in fibonacci cube graph ; return fibonacci number for f ( n + 2 ) ; 
def fib(n):
    if n <= 1:
        return n
    return fib(n - 1) + fib(n - 2)


def findVertices(n):
    return fib(n + 2)


if __name__ == "__main__":
    n = 3
    print(findVertices(n))

# Expected output:
5
# modify array such that the array does not contain any common divisors other than 1 | python3 program for the above approach ; function to check if it is possible to modify the array such that there is no common factor between array elements except 1 ; stores gcd of the array ; calculate gcd of the array ; if the current divisor is smaller than x ; divide gcd by the current divisor ; if possible ; print the modified array ; otherwise ; 

import math


def checkCommonDivisor(arr, N, X):
    G = 0
    for i in range(N):
        G = math .gcd(G, arr[i])
    copy_G = G
    for divisor in range(2, X + 1):
        while (G % divisor == 0):
            G = G // divisor
    if (G <= X):
        print("Yes")
        for i in range(N):
            print(arr[i] // copy_G, end=" ")
        print()
    else:
        print("No")


if __name__ == "__main__":
    arr = [6, 15, 6]
    X = 6
    N = len(arr)
    checkCommonDivisor(arr, N, X)

# Expected output:
Yes
2 5 2
# k 'th largest element in bst using constant extra space | helper function to create a new node ; count variable to keep count of visited nodes ; if right child is none ; first increment count and check if count = k ; otherwise move to the left child ; find inorder successor of current node ; set left child of successor to the current node ; move current to its right ; restoring the tree back to original binary search tree removing threaded links ; move current to its left child ; 

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


def KthLargestUsingMorrisTraversal(root, k):
    curr = root
    Klargest = None
    count = 0
    while (curr is not None):
        if (curr .right is None):
            count += 1
            if (count == k):
                Klargest = curr
            curr = curr .left
        else:
            succ = curr .right
            while (succ .left is not None and succ .left != curr):
                succ = succ .left
            if (succ .left is None):
                succ .left = curr
                curr = curr .right
            else:
                succ .left = None
                count += 1
                if (count == k):
                    Klargest = curr
                curr = curr .left
    return Klargest


if __name__ == '__main__':
    root = newNode(4)
    root .left = newNode(2)
    root .right = newNode(7)
    root .left .left = newNode(1)
    root .left .right = newNode(3)
    root .right .left = newNode(6)
    root .right .right = newNode(10)
    print("Finding K-th largest Node in BST : ",
          KthLargestUsingMorrisTraversal(root, 2).data)

# Expected output:
Finding K-th largest Node in BST :  7
# magic square | even order | function for calculating magic square ; 2 - d matrix with all entries as 0 ; change value of array elements at fix location as per the rule ( n * n + 1 ) - arr [ i ] [ [ j ] corners of order ( n / 4 ) * ( n / 4 ) top left corner ; top right corner ; bottom left corner ; bottom right corner ; centre of matrix , order ( n / 2 ) * ( n / 2 ) ; printing the square ; 
def DoublyEven(n):
    arr = [[(n*y)+x+1 for x in range(n)]for y in range(n)]
    for i in range(0, n//4):
        for j in range(0, n//4):
            arr[i][j] = (n*n + 1) - arr[i][j]
    for i in range(0, n//4):
        for j in range(3 * (n//4), n):
            arr[i][j] = (n*n + 1) - arr[i][j]
    for i in range(3 * (n//4), n):
        for j in range(0, n//4):
            arr[i][j] = (n*n + 1) - arr[i][j]
    for i in range(3 * (n//4), n):
        for j in range(3 * (n//4), n):
            arr[i][j] = (n*n + 1) - arr[i][j]
    for i in range(n//4, 3 * (n//4)):
        for j in range(n//4, 3 * (n//4)):
            arr[i][j] = (n*n + 1) - arr[i][j]
    for i in range(n):
        for j in range(n):
            print('%2d ' % (arr[i][j]), end=" ")
        print()


n = 8
DoublyEven(n)

# Expected output:
64  63   3   4   5   6  58  57  
56  55  11  12  13  14  50  49  
17  18  46  45  44  43  23  24  
25  26  38  37  36  35  31  32  
33  34  30  29  28  27  39  40  
41  42  22  21  20  19  47  48  
16  15  51  52  53  54  10   9  
 8   7  59  60  61  62   2   1
# kronecker product of two matrices | rowa and cola are no of rows and columns of matrix a rowb and colb are no of rows and columns of matrix b ; function to computes the kronecker product of two matrices ; i loops till rowa ; k loops till rowb ; j loops till cola ; l loops till colb ; each element of matrix a is multiplied by whole matrix b resp and stored as matrix c ; 

cola = 2
rowa = 3
colb = 3
rowb = 2


def Kroneckerproduct(A, B):
    C = [[0 for j in range(cola * colb)]for i in range(rowa * rowb)]
    for i in range(0, rowa):
        for k in range(0, rowb):
            for j in range(0, cola):
                for l in range(0, colb):
                    C[i + l + 1][j + k + 1] = A[i][j] * B[k][l]
                    print(C[i + l + 1][j + k + 1], end=' ')
            print("")


A = [[0 for j in range(2)]for i in range(3)]
B = [[0 for j in range(3)]for i in range(2)]
A[0][0] = 1
A[0][1] = 2
A[1][0] = 3
A[1][1] = 4
A[2][0] = 1
A[2][1] = 0
B[0][0] = 0
B[0][1] = 5
B[0][2] = 2
B[1][0] = 6
B[1][1] = 7
B[1][2] = 3
Kroneckerproduct(A, B)

# Expected output:
0 5 2 0 10 4 
6 7 3 12 14 6 
0 15 6 0 20 8 
18 21 9 24 28 12 
0 5 2 0 0 0 
6 7 3 0 0 0
# program to check if matrix is lower triangular | function to check matrix is in lower triangular ; 
def islowertriangular(M):
    for i in range(0, len(M)):
        for j in range(i + 1, len(M)):
            if (M[i][j] != 0):
                return False
    return True


M = [[1, 0, 0, 0], [1, 4, 0, 0], [4, 6, 2, 0], [0, 4, 7, 6]]
if islowertriangular(M):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# program to check if matrix is upper triangular | function to check matrix is in upper triangular ; 
def isuppertriangular(M):
    for i in range(1, len(M)):
        for j in range(0, i):
            if (M[i][j] != 0):
                return False
    return True


M = [[1, 3, 5, 3], [0, 4, 6, 2], [0, 0, 2, 5], [0, 0, 0, 6]]
if isuppertriangular(M):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# counting sets of 1 s and 0 s in a binary matrix | no of columns ; no of rows ; function to calculate the number of non empty sets of cell ; stores the final answer ; traverses row - wise ; traverses column wise ; at the end subtract n * m as no of single sets have been added twice . ; 

m = 3
n = 2


def countSets(a):
    res = 0
    for i in range(n):
        u = 0
        v = 0
        for j in range(m):
            if a[i][j]:
                u += 1
            else:
                v += 1
        res += pow(2, u) - 1 + pow(2, v) - 1
    for i in range(m):
        u = 0
        v = 0
        for j in range(n):
            if a[j][i]:
                u += 1
            else:
                v += 1
        res += pow(2, u) - 1 + pow(2, v) - 1
    return res - (n * m)


a = [[1, 0, 1], [0, 1, 0]]
print(countSets(a))

# Expected output:
8
# program to check if a matrix is symmetric | fills transpose of mat [ n ] [ n ] in tr [ n ] [ n ] ; returns true if mat [ n ] [ n ] is symmetric , else false ; 
def transpose(mat, tr, N):
    for i in range(N):
        for j in range(N):
            tr[i][j] = mat[j][i]


def isSymmetric(mat, N):
    tr = [[0 for j in range(len(mat[0]))]for i in range(len(mat))]
    transpose(mat, tr, N)
    for i in range(N):
        for j in range(N):
            if (mat[i][j] != tr[i][j]):
                return False
    return True


mat = [[1, 3, 5], [3, 2, 4], [5, 4, 1]]
if (isSymmetric(mat, 3)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# program to check if a matrix is symmetric | returns true if mat [ n ] [ n ] is symmetric , else false ; 
def isSymmetric(mat, N):
    for i in range(N):
        for j in range(N):
            if (mat[i][j] != mat[j][i]):
                return False
    return True


mat = [[1, 3, 5], [3, 2, 4], [5, 4, 1]]
if (isSymmetric(mat, 3)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes