giulio98/xlcost-single-prompt huggingface dataset:
# morse code implementation | function to encode a alphabet as morse code ; refer to the morse table image attached in the article ; for space ; character by character print morse code ; 
def morseEncode(x):
    if x is 'a':
        return ".-"
    elif x is 'b':
        return "-..."
    elif x is 'c':
        return "-.-."
    elif x is 'd':
        return "-.."
    elif x is 'e':
        return "."
    elif x is 'f':
        return "..-."
    elif x is 'g':
        return "--."
    elif x is 'h':
        return "...."
    elif x is 'i':
        return ".."
    elif x is 'j':
        return ".---"
    elif x is 'k':
        return "-.-"
    elif x is 'l':
        return ".-.."
    elif x is 'm':
        return "--"
    elif x is 'n':
        return "-."
    elif x is 'o':
        return "---"
    elif x is 'p':
        return ".--."
    elif x is 'q':
        return "--.-"
    elif x is 'r':
        return ".-."
    elif x is 's':
        return "..."
    elif x is 't':
        return "-"
    elif x is 'u':
        return "..-"
    elif x is 'v':
        return "...-"
    elif x is 'w':
        return ".--"
    elif x is 'x':
        return "-..-"
    elif x is 'y':
        return "-.--"
    elif x is 'z':
        return "--.."
    elif x is '1':
        return ".----"
    elif x is '2':
        return "..---"
    elif x is '3':
        return "...--"
    elif x is '4':
        return "....-"
    elif x is '5':
        return "....."
    elif x is '6':
        return "-...."
    elif x is '7':
        return "--..."
    elif x is '8':
        return "---.."
    elif x is '9':
        return "----."
    elif x is '0':
        return "-----"


def morseCode(s):
    for character in s:
        print(morseEncode(character), end="")


if __name__ == "__main__":
    s = "geeksforgeeks"
    morseCode(s)

# Expected output:
--...-.-.....-.---.-.--...-.-...
# polybius square cipher | function to display polybius cipher text ; convert each character to its encrypted code ; finding row of the table ; finding column of the table ; if character is 'k ; if character is greater than 'j ; 
def polybiusCipher(s):

    for char in s:

        row = int((ord(char) - ord('a')) / 5) + 1

        col = ((ord(char) - ord('a')) % 5) + 1

        if char == 'k':
            row = row - 1
            col = 5 - col + 1

        elif ord(char) >= ord('j'):
            if col == 1:
                col = 6
                row = row - 1

            col = col - 1

        print(row, col, end='', sep='')


if __name__ == "__main__":

    s = "geeksforgeeks"

    polybiusCipher(s)

# Expected output:
22151525432134422215152543
# longest uncommon subsequence | python program to find longest uncommon subsequence using naive method ; function to calculate length of longest uncommon subsequence ; case 1 : if strings are equal ; for case 2 and case 3 ; 

import math


def findLUSlength(a, b):
    if (a == b):
        return 0
    return max(len(a), len(b))


a = "abcdabcd"
b = "abcabc"
print(findLUSlength(a, b))

# Expected output:
8
# interchanging first and second halves of strings | function to concatenate two different halves of given strings ; creating new strings by exchanging the first half of a and b . please refer below for details of substr . https : www . geeksforgeeks . org / stdsubstr - in - ccpp / ; 
def swapTwoHalves(a, b):
    la = len(a)
    lb = len(b)
    c = a[0:la // 2] + b[lb // 2:lb]
    d = b[0:lb // 2] + a[la // 2:la]
    print(c, "", d)


a = "remuneration"
b = "day"
swapTwoHalves(a, b)

# Expected output:
remuneay  dration
# magical indices in an array | function to count number of magical indices . ; array to store parent node of traversal . ; array to determine whether current node is already counted in the cycle . ; initialize the arrays . ; check if current node is already traversed or not . if node is not traversed yet then parent value will be - 1. ; traverse the graph until an already visited node is not found . ; check parent value to ensure a cycle is present . ; count number of nodes in the cycle . ; 
def solve(A, n):
    cnt = 0
    parent = [None] * (n + 1)
    vis = [None] * (n + 1)
    for i in range(0, n + 1):
        parent[i] = -1
        vis[i] = 0
    for i in range(0, n):
        j = i
        if (parent[j] == -1):
            while (parent[j] == -1):
                parent[j] = i
                j = (j + A[j] + 1) % n
            if (parent[j] == i):
                while (vis[j] == 0):
                    vis[j] = 1
                    cnt = cnt + 1
                    j = (j + A[j] + 1) % n
    return cnt


A = [0, 0, 0, 2]
n = len(A)
print(solve(A, n))

# Expected output:
2
# longest path between any pair of vertices | visited [ ] array to make nodes visited src is starting node for dfs traversal prev_len is sum of cable length till current node max_len is pointer which stores the maximum length of cable value after dfs traversal ; mark the src node visited ; curr_len is for length of cable from src city to its adjacent city ; adjacent is pair type which stores destination city and cable length ; traverse all adjacent ; adjacent element ; if node or city is not visited ; total length of cable from src city to its adjacent ; call dfs for adjacent city ; if total cable length till now greater than previous length then update it ; make curr_len = 0 for next adjacent ; n is number of cities or nodes in graph cable_lines is total cable_lines among the cities or edges in graph ; maximum length of cable among the connected cities ; call dfs for each city to find maximum length of cable ; initialize visited array with 0 ; call dfs for src vertex i ; 
def DFS(graph, src, prev_len, max_len, visited):
    visited[src] = 1
    curr_len = 0
    adjacent = None
    for i in range(len(graph[src])):
        adjacent = graph[src][i]
        if (not visited[adjacent[0]]):
            curr_len = prev_len + adjacent[1]
            DFS(graph, adjacent[0], curr_len, max_len, visited)
        if (max_len[0] < curr_len):
            max_len[0] = curr_len
        curr_len = 0


def longestCable(graph, n):
    max_len = [-999999999999]
    for i in range(1, n + 1):
        visited = [False] * (n + 1)
        DFS(graph, i, 0, max_len, visited)
    return max_len[0]


if __name__ == '__main__':
    n = 6
    graph = [[]for i in range(n + 1)]
    graph[1].append([2, 3])
    graph[2].append([1, 3])
    graph[2].append([3, 4])
    graph[3].append([2, 4])
    graph[2].append([6, 2])
    graph[6].append([2, 2])
    graph[4].append([6, 6])
    graph[6].append([4, 6])
    graph[5].append([6, 5])
    graph[6].append([5, 5])
    print("Maximum length of cable =", longestCable(graph, n))

# Expected output:
Maximum length of cable = 12
# level order traversal with direction change after every two levels | a binary tree node ; function to prthe level order of given binary tree . direction of printing level order traversal of binary tree changes after every two levels ; for null root ; maintain a queue for normal level order traversal ; maintain a stack for printing nodes in reverse order after they are popped out from queue . ; sz is used for storing the count of nodes in a level ; used for changing the direction of level order traversal ; used for changing the direction of level order traversal ; push root node to the queue ; run this while loop till queue got empty ; do a normal level order traversal ; for printing nodes from left to right , simply prthe nodes in the order in which they are being popped out from the queue . ; for printing nodes from right to left , push the nodes to stack instead of printing them . ; for printing the nodes in order from right to left ; change the direction of printing nodes after every two levels . ; 

from collections import deque


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


def modifiedLevelOrder(node):
    if (node is None):
        return
    if (node .left is None and node .right is None):
        print(node .data, end=" ")
        return
    myQueue = deque()
    myStack = []
    temp = None
    sz = 0
    ct = 0
    rightToLeft = False
    myQueue .append(node)
    while (len(myQueue) > 0):
        ct += 1
        sz = len(myQueue)
        for i in range(sz):
            temp = myQueue .popleft()
            if (rightToLeft == False):
                print(temp .data, end=" ")
            else:
                myStack .append(temp)
            if (temp .left):
                myQueue .append(temp .left)
            if (temp .right):
                myQueue .append(temp .right)
        if (rightToLeft):
            while (len(myStack) > 0):
                temp = myStack[-1]
                del myStack[-1]
                print(temp .data, end=" ")
        if (ct == 2):
            rightToLeft = not rightToLeft
            ct = 0
        print()


if __name__ == '__main__':
    root = Node(1)
    root .left = Node(2)
    root .right = Node(3)
    root .left .left = Node(4)
    root .left .right = Node(5)
    root .right .left = Node(6)
    root .right .right = Node(7)
    root .left .left .left = Node(8)
    root .left .left .right = Node(9)
    root .left .right .left = Node(3)
    root .left .right .right = Node(1)
    root .right .left .left = Node(4)
    root .right .left .right = Node(2)
    root .right .right .left = Node(7)
    root .right .right .right = Node(2)
    root .left .right .left .left = Node(16)
    root .left .right .left .right = Node(17)
    root .right .left .right .left = Node(18)
    root .right .right .left .right = Node(19)
    modifiedLevelOrder(root)

# Expected output:
1 
2 3 
7 6 5 4 
2 7 2 4 1 3 9 8 
16 17 18 19
# minimum cost to connect all cities | function to find out minimum valued node among the nodes which are not yet included in mst ; loop through all the values of the nodes which are not yet included in mst and find the minimum valued one . ; function to find out the mst and the cost of the mst . ; array to store the parent node of a particular node . ; array to store key value of each node . ; boolean array to hold bool values whether a node is included in mst or not . ; set all the key values to infinite and none of the nodes is included in mst . ; start to find the mst from node 0. parent of node 0 is none so set - 1. key value or minimum cost to reach 0 th node from 0 th node is 0. ; find the rest n - 1 nodes of mst . ; first find out the minimum node among the nodes which are not yet included in mst . ; now the uth node is included in mst . ; update the values of neighbor nodes of u which are not yet included in mst . ; find out the cost by adding the edge values of mst . ; 
def minnode(n, keyval, mstset):
    mini = 999999999999
    mini_index = None
    for i in range(n):
        if (mstset[i] == False and keyval[i] < mini):
            mini = keyval[i]
            mini_index = i
    return mini_index


def findcost(n, city):
    parent = [None] * n
    keyval = [None] * n
    mstset = [None] * n
    for i in range(n):
        keyval[i] = 9999999999999
        mstset[i] = False
    parent[0] = -1
    keyval[0] = 0
    for i in range(n - 1):
        u = minnode(n, keyval, mstset)
        mstset[u] = True
        for v in range(n):
            if (city[u][v] and mstset[v] == False and city[u][v] < keyval[v]):
                keyval[v] = city[u][v]
                parent[v] = u
    cost = 0
    for i in range(1, n):
        cost += city[parent[i]][i]
    print(cost)


if __name__ == '__main__':
    n1 = 5
    city1 = [[0, 1, 2, 3, 4], [1, 0, 5, 0, 7], [
        2, 5, 0, 6, 0], [3, 0, 6, 0, 0], [4, 7, 0, 0, 0]]
    findcost(n1, city1)
    n2 = 6
    city2 = [[0, 1, 1, 100, 0, 0], [1, 0, 1, 0, 0, 0], [1, 1, 0, 0, 0, 0], [
        100, 0, 0, 0, 2, 2], [0, 0, 0, 2, 0, 2], [0, 0, 0, 2, 2, 0]]
    findcost(n2, city2)

# Expected output:
10
106
# minimum product spanning tree | a python3 program for getting minimum product spanning tree the program is for adjacency matrix representation of the graph ; number of vertices in the graph ; a utility function to find the vertex with minimum key value , from the set of vertices not yet included in mst ; initialize min value ; a utility function to print the constructed mst stored in parent [ ] and print minimum obtaiable product ; function to construct and print mst for a graph represented using adjacency matrix representation inputgraph is sent for printing actual edges and loggraph is sent for actual mst operations ; array to store constructed mst ; key values used to pick minimum ; weight edge in cut to represent set of vertices not ; always include first 1 st vertex in mst make key 0 so that this vertex is ; picked as first vertex first node is always root of mst ; the mst will have v vertices ; pick the minimum key vertex from the set of vertices not yet included in mst ; add the picked vertex to the mst set ; update key value and parent index of the adjacent vertices of the picked vertex . consider only those vertices which are not yet included in mst ; loggraph [ u ] [ v ] is non zero only for adjacent vertices of m mstset [ v ] is false for vertices not yet included in mst . update the key only if loggraph [ u ] [ v ] is smaller than key [ v ] ; print the constructed mst ; method to get minimum product spanning tree ; constructing loggraph from original graph ; applyting standard prim 's mst algorithm  on log graph. ; 

import math
V = 5


def minKey(key, mstSet):
    min = 10000000
    min_index = 0
    for v in range(V):
        if (mstSet[v] == False and key[v] < min):
            min = key[v]
            min_index = v
    return min_index


def printMST(parent, n, graph):
    print("Edge Weight")
    minProduct = 1
    for i in range(1, V):
        print("{} - {} {} ".format(parent[i], i, graph[i][parent[i]]))
        minProduct *= graph[i][parent[i]]
    print("Minimum Obtainable product is {}".format(minProduct))


def primMST(inputGraph, logGraph):
    parent = [0 for i in range(V)]
    key = [10000000 for i in range(V)]
    mstSet = [False for i in range(V)]
    key[0] = 0
    parent[0] = -1
    for count in range(0, V - 1):
        u = minKey(key, mstSet)
        mstSet[u] = True
        for v in range(V):
            if (logGraph[u][v] > 0 and mstSet[v] ==
                    False and logGraph[u][v] < key[v]):
                parent[v] = u
                key[v] = logGraph[u][v]
    printMST(parent, V, inputGraph)


def minimumProductMST(graph):
    logGraph = [[0 for j in range(V)]for i in range(V)]
    for i in range(V):
        for j in range(V):
            if (graph[i][j] > 0):
                logGraph[i][j] = math .log(graph[i][j])
            else:
                logGraph[i][j] = 0
    primMST(graph, logGraph)


if __name__ == '__main__':
    graph = [[0, 2, 0, 6, 0], [2, 0, 3, 8, 5], [
        0, 3, 0, 0, 7], [6, 8, 0, 0, 9], [0, 5, 7, 9, 0], ]
    minimumProductMST(graph)

# Expected output:
Edge Weight
0 - 1 2 
1 - 2 3 
0 - 3 6 
1 - 4 5 
Minimum Obtainable product is 180
# tug of war | function that tries every possible solution by calling itself recursively ; checks whether the it is going out of bound ; checks that the numbers of elements left are not less than the number of elements required to form the solution ; consider the cases when current element is not included in the solution ; add the current element to the solution ; checks if a solution is formed ; checks if the solution formed is better than the best solution so far ; consider the cases where current element is included in the solution ; removes current element before returning to the caller of this function ; main function that generate an arr ; the boolean array that contains the inclusion and exclusion of an element in current set . the number excluded automatically form the other set ; the inclusion / exclusion array for final solution ; find the solution using recursive function towutil ( ) ; print the solution ; 
def TOWUtil(
        arr,
        n,
        curr_elements,
        no_of_selected_elements,
        soln,
        min_diff,
        Sum,
        curr_sum,
        curr_position):
    if (curr_position == n):
        return
    if ((int(n / 2) - no_of_selected_elements) > (n - curr_position)):
        return
    TOWUtil(
        arr,
        n,
        curr_elements,
        no_of_selected_elements,
        soln,
        min_diff,
        Sum,
        curr_sum,
        curr_position + 1)
    no_of_selected_elements += 1
    curr_sum = curr_sum + arr[curr_position]
    curr_elements[curr_position] = True
    if (no_of_selected_elements == int(n / 2)):
        if (abs(int(Sum / 2) - curr_sum) < min_diff[0]):
            min_diff[0] = abs(int(Sum / 2) - curr_sum)
            for i in range(n):
                soln[i] = curr_elements[i]
    else:
        TOWUtil(
            arr,
            n,
            curr_elements,
            no_of_selected_elements,
            soln,
            min_diff,
            Sum,
            curr_sum,
            curr_position + 1)
    curr_elements[curr_position] = False


def tugOfWar(arr, n):
    curr_elements = [None] * n
    soln = [None] * n
    min_diff = [999999999999]
    Sum = 0
    for i in range(n):
        Sum += arr[i]
        curr_elements[i] = soln[i] = False
    TOWUtil(arr, n, curr_elements, 0, soln, min_diff, Sum, 0, 0)
    print("The first subset is: ")
    for i in range(n):
        if (soln[i]):
            print(arr[i], end=" ")
    print()
    print("The second subset is: ")
    for i in range(n):
        if (soln[i] == False):
            print(arr[i], end=" ")


if __name__ == '__main__':
    arr = [23, 45, -34, 12, 0, 98, -99, 4, 189, -1, 4]
    n = len(arr)
    tugOfWar(arr, n)

# Expected output:
The first subset is: 
45 -34 12 98 -1 
The second subset is: 
23 0 -99 4 189 4
# rat in a maze | backtracking | maze size ; a utility function to print solution matrix sol ; a utility function to check if x , y is valid index for n * n maze ; if ( x , y outside maze ) return false ; this function solves the maze problem using backtracking . it mainly uses solvemazeutil ( ) to solve the problem . it returns false if no path is possible , otherwise return true and prints the path in the form of 1 s . please note that there may be more than one solutions , this function prints one of the feasable solutions . ; a recursive utility function to solve maze problem ; if ( x , y is goal ) return true ; check if maze [ x ] [ y ] is valid ; check if the current block is already part of solution path . ; mark x , y as part of solution path ; move forward in x direction ; if moving in x direction doesn 't give solution  then move down in y direction ; if moving in y direction doesn 't give solution then  move back in x direction ; if moving in backwards in x direction doesn 't give solution  then move upwards in y direction ; if none of the above movements work then backtrack : unmark x , y as part of solution path ; 

N = 4


def printSolution(sol):
    for i in sol:
        for j in i:
            print(str(j) + " ", end="")
        print("")


def isSafe(maze, x, y):
    if x >= 0 and x < N and y >= 0 and y < N and maze[x][y] == 1:
        return True
    return False


def solveMazeUtil(maze, x, y, sol):
    if x == N - 1 and y == N - 1 and maze[x][y] == 1:
        sol[x][y] = 1
        return True
    if isSafe(maze, x, y):
        if sol[x][y] == 1:
            return False
        sol[x][y] = 1
        if solveMazeUtil(maze, x + 1, y, sol):
            return True
        if solveMazeUtil(maze, x, y + 1, sol):
            return True
        if solveMazeUtil(maze, x - 1, y, sol):
            return True
        if solveMazeUtil(maze, x, y - 1, sol):
            return True
        sol[x][y] = 0
        return False


def solveMaze(maze):
    sol = [[0 for j in range(4)]for i in range(4)]
    if solveMazeUtil(maze, 0, 0, sol) == False:
        print("Solution doesn't exist")
        return False
    printSolution(sol)
    return True


if __name__ == "__main__":
    maze = [[1, 0, 0, 0], [1, 1, 0, 1], [0, 1, 0, 0], [1, 1, 1, 1]]
    solveMaze(maze)

# Expected output:
1 0 0 0 
1 1 0 0 
0 1 0 0 
0 1 1 1
# m coloring problem | backtracking | a utility function to prsolution ; check if the colored graph is safe or not ; check for every edge ; this function solves the m coloring problem using recursion . it returns false if the m colours cannot be assigned , otherwise , return true and prints assignments of colours to all vertices . please note that there may be more than one solutions , this function prints one of the feasible solutions . ; if current index reached end ; if coloring is safe ; prthe solution ; assign each color from 1 to m ; recur of the rest vertices ; 
def printSolution(color):
    print("Solution Exists:" " Following are the assigned colors ")
    for i in range(4):
        print(color[i], end=" ")


def isSafe(graph, color):
    for i in range(4):
        for j in range(i + 1, 4):
            if (graph[i][j] and color[j] == color[i]):
                return False
    return True


def graphColoring(graph, m, i, color):
    if (i == 4):
        if (isSafe(graph, color)):
            printSolution(color)
            return True
        return False
    for j in range(1, m + 1):
        color[i] = j
        if (graphColoring(graph, m, i + 1, color)):
            return True
        color[i] = 0
    return False


if __name__ == '__main__':
    graph = [[0, 1, 1, 1], [1, 0, 1, 0], [1, 1, 0, 1], [1, 0, 1, 0], ]
    m = 3
    color = [0 for i in range(4)]
    if (not graphColoring(graph, m, 0, color)):
        print("Solution does not exist")

# Expected output:
Solution Exists: Following are the assigned colors 
1 2 3 2
# maximize pair decrements required to reduce all array elements except one to 0 | function to count maximum number of steps to make ( n - 1 ) array elements to 0 ; stores maximum count of steps to make ( n - 1 ) elements equal to 0 ; stores array elements ; traverse the array ; insert arr [ i ] into pq ; extract top 2 elements from the array while ( n - 1 ) array elements become 0 ; stores top element of pq ; pop the top element of pq . ; stores top element of pq ; pop the top element of pq . ; update x ; update y ; if x is not equal to 0 ; insert x into pq ; if y is not equal to 0 ; insert y into pq ; update cntop ; 
def cntMaxOperationToMakeN_1_0(arr, N):
    cntOp = 0
    PQ = []
    for i in range(N):
        PQ .append(arr[i])
    PQ = sorted(PQ)
    while (len(PQ) > 1):
        X = PQ[-1]
        del PQ[-1]
        Y = PQ[-1]
        del PQ[-1]
        X -= 1
        Y -= 1
        if (X != 0):
            PQ .append(X)
        if (Y != 0):
            PQ .append(Y)
        cntOp += 1
        PQ = sorted(PQ)
    return cntOp


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

# Expected output:
7
# flip all k | function to flip all k - bits of an unsigned number n ; stores ( 2 ^ k ) - 1 ; update n ; print the answer ; 
def flippingBits(N, K):
    X = (1 << (K - 1)) - 1
    N = X - N
    print(N)


if __name__ == '__main__':
    N, K = 1, 8
    flippingBits(N, K)

# Expected output:
126
# generate a matrix having even sum of all diagonals in each 2 x 2 submatrices | function to construct a matrix such that the sum elements in both diagonals of every 2 * 2 matrices is even ; stores odd numbers ; stores even numbers ; store matrix elements such that sum of elements in both diagonals of every 2 * 2 submatrices is even ; fill all the values of matrix elements ; update odd ; update even ; prthe matrix ; 
def generateMatrix(N):
    odd = 1
    even = 2
    mat = [[0 for i in range(N + 1)]for j in range(N + 1)]
    for i in range(1, N + 1):
        for j in range(1, N + 1):
            if ((i + j) % 2 == 0):
                mat[i][j] = odd
                odd += 2
            else:
                mat[i][j] = even
                even += 2
    for i in range(1, N + 1):
        for j in range(1, N + 1):
            print(mat[i][j], end=" ")
        print()


if __name__ == '__main__':
    N = 4
    generateMatrix(N)

# Expected output:
1 2 3 4 
6 5 8 7 
9 10 11 12 
14 13 16 15