giulio98/xlcost-single-prompt huggingface dataset:
# eulerian path in undirected graph | function to find out the path it takes the adjacency matrix representation of the graph as input ; find out number of edges each vertex has ; find out how many vertex has odd number edges ; if number of vertex with odd number of edges is greater than two return " no ▁ solution " . ; if there is a path find the path initialize empty stack and path take the starting current as discussed ; loop will run until there is element in the stack or current edge has some neighbour . ; if current node has not any neighbour add it to path and pop stack set new current to the popped element ; if the current vertex has at least one neighbour add the current vertex to stack , remove the edge between them and set the current to its neighbour . ; print the path ; 
def findpath(graph, n):
    numofadj = []
    for i in range(n):
        numofadj .append(sum(graph[i]))
    startpoint, numofodd = 0, 0
    for i in range(n - 1, -1, -1):
        if (numofadj[i] % 2 == 1):
            numofodd += 1
            startpoint = i
    if (numofodd > 2):
        print("No Solution")
        return
    stack = []
    path = []
    cur = startpoint
    while (len(stack) > 0 or sum(graph[cur]) != 0):
        if (sum(graph[cur]) == 0):
            path .append(cur)
            cur = stack[-1]
            del stack[-1]
        else:
            for i in range(n):
                if (graph[cur][i] == 1):
                    stack .append(cur)
                    graph[cur][i] = 0
                    graph[i][cur] = 0
                    cur = i
                    break
    for ele in path:
        print(ele, end=" -> ")
    print(cur)


if __name__ == '__main__':
    graph1 = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [
        0, 1, 0, 1, 0], [0, 1, 1, 0, 0], [1, 0, 0, 0, 0]]
    n = len(graph1)
    findpath(graph1, n)
    graph2 = [[0, 1, 0, 1, 1], [1, 0, 1, 0, 1], [
        0, 1, 0, 1, 1], [1, 1, 1, 0, 0], [1, 0, 1, 0, 0]]
    n = len(graph2)
    findpath(graph2, n)
    graph3 = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 1], [
        0, 1, 0, 1, 0], [0, 1, 1, 0, 1], [1, 1, 0, 1, 0]]
    n = len(graph3)
    findpath(graph3, n)

# Expected output:
4 -> 0 -> 1 -> 3 -> 2 -> 1
No Solution
4 -> 3 -> 2 -> 1 -> 4 -> 0 -> 1 -> 3
# array element with minimum sum of absolute differences | function to return the minimized sum ; sort the array ; median of the array ; calculate the minimized sum ; return the required sum ; 
def minSum(arr, n):
    arr .sort()
    x = arr[n // 2]
    sum = 0
    for i in range(n):
        sum += abs(arr[i] - x)
    return sum


if __name__ == "__main__":
    arr = [1, 3, 9, 3, 6]
    n = len(arr)
    print(minSum(arr, n))

# Expected output:
11
# sort even and odd placed elements in increasing order | function to prin the odd and even indexed digits ; lists to store the odd and even positioned digits ; traverse through all the indexes in the integer ; if the digit is in odd_index position append it to odd_position list ; else append it to the even_position list ; print the elements in the list in sorted order ; 
def odd_even(n):
    odd_indexes = []
    even_indexes = []
    for i in range(len(n)):
        if i % 2 == 0:
            odd_indexes .append(n[i])
        else:
            even_indexes .append(n[i])
    for i in sorted(odd_indexes):
        print(i, end=" ")
    for i in sorted(even_indexes):
        print(i, end=" ")


n = [3, 2, 7, 6, 8]
odd_even(n)

# Expected output:
3 7 8 2 6
# number of pairs whose sum is a power of 2 | function to return the count of valid pairs ; storing occurrences of each element ; sort the array in deceasing order ; start taking largest element each time ; if element has already been paired ; find the number which is greater than a [ i ] and power of two ; if there is a number which adds up with a [ i ] to form a power of two ; edge case when a [ i ] and crr - a [ i ] is same and we have only one occurrence of a [ i ] then it cannot be paired ; remove already paired elements ; return the count ; 
def countPairs(a, n):
    mp = dict .fromkeys(a, 0)
    for i in range(n):
        mp[a[i]] += 1
    a .sort(reverse=True)
    count = 0
    for i in range(n):
        if (mp[a[i]] < 1):
            continue
        cur = 1
        while (cur <= a[i]):
            cur = cur << 1
        if (cur - a[i] in mp .keys()):
            if (cur - a[i] == a[i] and mp[a[i]] == 1):
                continue
            count += 1
            mp[cur - a[i]] -= 1
            mp[a[i]] -= 1
    return count


if __name__ == "__main__":
    a = [3, 11, 14, 5, 13]
    n = len(a)
    print(countPairs(a, n))

# Expected output:
2
# maximizing the elements with a [ i + 1 ] > a [ i ] | returns the number of positions where a ( i + 1 ) is greater than a ( i ) after rearrangement of the array ; creating a hashmap containing char as a key and occurrences as a value ; find the maximum frequency ; 
def countMaxPos(arr):
    n = len(arr)
    Map = {}
    for x in arr:
        if x in Map:
            Map[x] += 1
        else:
            Map[x] = 1
    max_freq = 0
    for entry in Map:
        max_freq = max(max_freq, Map[entry])
    return n - max_freq


if __name__ == "__main__":
    arr = [20, 30, 10, 50, 40]
    print(countMaxPos(arr))

# Expected output:
4
# permutation of an array that has smaller values from another array | function to print required permutation ; storing elements and indexes ; filling the answer array ; pair element of a and b ; fill the remaining elements of answer ; output required permutation ; 
def anyPermutation(A, B, n):
    Ap, Bp = [], []
    for i in range(0, n):
        Ap .append([A[i], i])
    for i in range(0, n):
        Bp .append([B[i], i])
    Ap .sort()
    Bp .sort()
    i, j = 0, 0,
    ans = [0] * n
    remain = []
    while i < n and j < n:
        if Ap[i][0] > Bp[j][0]:
            ans[Bp[j][1]] = Ap[i][0]
            i += 1
            j += 1
        else:
            remain .append(i)
            i += 1
    j = 0
    for i in range(0, n):
        if ans[i] == 0:
            ans[i] = Ap[remain[j]][0]
            j += 1
    for i in range(0, n):
        print(ans[i], end=" ")


if __name__ == "__main__":
    A = [12, 24, 8, 32]
    B = [13, 25, 32, 11]
    n = len(A)
    anyPermutation(A, B, n)

# Expected output:
24 32 8 12
# rearrange all elements of array which are multiples of x in increasing order | function to sort all the multiples of x from the array in ascending order ; insert all multiples of 5 to a vector ; sort the vector ; update the array elements ; 
def sortMultiples(arr, n, x):
    v = []
    for i in range(0, n, 1):
        if (arr[i] % x == 0):
            v .append(arr[i])
    v .sort(reverse=False)
    j = 0
    for i in range(0, n, 1):
        if (arr[i] % x == 0):
            arr[i] = v[j]
            j += 1


if __name__ == '__main__':
    arr = [125, 3, 15, 6, 100, 5]
    x = 5
    n = len(arr)
    sortMultiples(arr, n, x)
    for i in range(0, n, 1):
        print(arr[i], end=" ")

# Expected output:
5 3 15 6 100 125
# minimum increment in the sides required to get non | function to return the minimum increase in side lengths of the triangle ; push the three sides to a array ; sort the array ; check if sum is greater than third side ; 
def minimumIncrease(a, b, c):
    arr = sorted([a, b, c])
    if arr[0] + arr[1] >= arr[2]:
        return 0
    else:
        return arr[2] - (arr[0] + arr[1])


if __name__ == "__main__":
    a, b, c = 3, 5, 10
    print(minimumIncrease(a, b, c))

# Expected output:
2
# minimum sum of differences with an element in an array | function to find min sum after operation ; sort the array ; pick middle value ; sum of absolute differences . ; 
def absSumDidd(a, n):
    a .sort()
    midValue = a[(int)(n // 2)]
    sum = 0
    for i in range(n):
        sum = sum + abs(a[i] - midValue)
    return sum


arr = [5, 11, 14, 10, 17, 15]
n = len(arr)
print(absSumDidd(arr, n))

# Expected output:
20
# printing frequency of each character just after its consecutive occurrences | python 3 program to print run length encoding of a string ; counting occurrences of s [ i ] ; 
def printRLE(s):
    i = 0
    while (i < len(s) - 1):
        count = 1
        while s[i] == s[i + 1]:
            i += 1
            count += 1
            if i + 1 == len(s):
                break
        print(str(s[i]) + str(count), end=" ")
        i += 1
    print()


if __name__ == "__main__":
    printRLE("GeeeEEKKKss")
    printRLE("cccc0ddEEE")

# Expected output:
G1 e3 E2 K3 s2 
c4 01 d2 E3
# word ladder ( length of shortest chain to reach a target word ) | python3 program to find length of the shortest chain transformation from source to target ; returns length of shortest chain to reach ' target ' from ' start ' using minimum number of adjacent moves . d is dictionary ; if the target is not present in the dictionary ; to store the current chain length and the length of the words ; push the starting word into the queue ; while the queue is non - empty ; increment the chain length ; current size of the queue ; since the queue is being updated while it is being traversed so only the elements which were already present in the queue before the start of this loop will be traversed for now ; remove the first word from the queue ; for every character of the word ; retain the original character at the current position ; replace the current character with every possible lowercase alphabet ; if the new word is equal to the target word ; remove the word from the set if it is found in it ; and push the newly generated word which will be a part of the chain ; restore the original character at the current position ; 

from collections import deque


def shortestChainLen(start, target, D):
    if start == target:
        return 0
    if target not in D:
        return 0
    level, wordlength = 0, len(start)
    Q = deque()
    Q .append(start)
    while (len(Q) > 0):
        level += 1
        sizeofQ = len(Q)
        for i in range(sizeofQ):
            word = [j for j in Q .popleft()]
            for pos in range(wordlength):
                orig_char = word[pos]
                for c in range(ord('a'), ord('z') + 1):
                    word[pos] = chr(c)
                    if ("".join(word) == target):
                        return level + 1
                    if ("".join(word)not in D):
                        continue
                    del D["".join(word)]
                    Q .append("".join(word))
                word[pos] = orig_char
    return 0


if __name__ == '__main__':
    D = {}
    D["poon"] = 1
    D["plee"] = 1
    D["same"] = 1
    D["poie"] = 1
    D["plie"] = 1
    D["poin"] = 1
    D["plea"] = 1
    start = "toon"
    target = "plea"
    print("Length of shortest chain is: ", shortestChainLen(start, target, D))

# Expected output:
Length of shortest chain is:  7
# find if an array of strings can be chained to form a circle | set 2 | python3 code to check if cyclic order is possible among strings under given constrainsts ; utility method for a depth first search among vertices ; returns true if all vertices are strongly connected i . e . can be made as loop ; initialize all vertices as not visited ; perform a dfs from s ; now loop through all characters ; i character is marked ( i . e . it was first or last character of some string ) then it should be visited in last dfs ( as for looping , graph should be strongly connected ) ; if we reach that means graph is connected ; return true if an order among strings is possible ; create an empty graph ; initialize all vertices as not marked ; initialize indegree and outdegree of every vertex as 0. ; process all strings one by one ; find first and last characters ; mark the characters ; increase indegree and outdegree count ; add an edge in graph ; if for any character indegree is not equal to outdegree then ordering is not possible ; 

M = 26


def dfs(g, u, visit):
    visit[u] = True
    for i in range(len(g[u])):
        if (not visit[g[u][i]]):
            dfs(g, g[u][i], visit)


def isConnected(g, mark, s):
    visit = [False for i in range(M)]
    dfs(g, s, visit)
    for i in range(M):
        if (mark[i] and (not visit[i])):
            return False
    return True


def possibleOrderAmongString(arr, N):
    g = {}
    mark = [False for i in range(M)]
    In = [0 for i in range(M)]
    out = [0 for i in range(M)]
    for i in range(N):
        f = (ord(arr[i][0]) - ord('a'))
        l = (ord(arr[i][-1]) - ord('a'))
        mark[f] = True
        mark[l] = True
        In[l] += 1
        out[f] += 1
        if f not in g:
            g[f] = []
        g[f].append(l)
    for i in range(M):
        if (In[i] != out[i]):
            return False
    return isConnected(g, mark, ord(arr[0][0]) - ord('a'))


arr = ["ab", "bc", "cd", "de", "ed", "da"]
N = len(arr)
if (possibleOrderAmongString(arr, N) == False):
    print("Ordering not possible")
else:
    print("Ordering is possible")

# Expected output:
Ordering is possible
# dynamic connectivity | set 1 ( incremental ) | finding the root of node i ; union of two nodes a and b ; union based on rank ; returns true if two nodes have same root ; performing an operation according to query type ; type 1 query means checking if node x and y are connected or not ; if roots of x and y is same then yes is the answer ; type 2 query refers union of x and y ; if x and y have different roots then union them ; 
def root(arr, i):
    while (arr[i] != i):
        arr[i] = arr[arr[i]]
        i = arr[i]
    return i


def weighted_union(arr, rank, a, b):
    root_a = root(arr, a)
    root_b = root(arr, b)
    if (rank[root_a] < rank[root_b]):
        arr[root_a] = arr[root_b]
        rank[root_b] += rank[root_a]
    else:
        arr[root_b] = arr[root_a]
        rank[root_a] += rank[root_b]


def areSame(arr, a, b):
    return (root(arr, a) == root(arr, b))


def query(type, x, y, arr, rank):
    if (type == 1):
        if (areSame(arr, x, y)):
            print("Yes")
        else:
            print("No")
    elif (type == 2):
        if (areSame(arr, x, y) == False):
            weighted_union(arr, rank, x, y)


if __name__ == '__main__':
    n = 7
    arr = [None] * n
    rank = [None] * n
    for i in range(n):
        arr[i] = i
        rank[i] = 1
    q = 11
    query(1, 0, 1, arr, rank)
    query(2, 0, 1, arr, rank)
    query(2, 1, 2, arr, rank)
    query(1, 0, 2, arr, rank)
    query(2, 0, 2, arr, rank)
    query(2, 2, 3, arr, rank)
    query(2, 3, 4, arr, rank)
    query(1, 0, 5, arr, rank)
    query(2, 4, 5, arr, rank)
    query(2, 5, 6, arr, rank)
    query(1, 2, 6, arr, rank)

# Expected output:
No
Yes
No
Yes
# perfect binary tree specific level order traversal | a binary tree ndoe ; given a perfect binary tree print its node in specific order ; let us print root and next level first ; since it is perfect binary tree , one of the node is needed to be checked ; do anythong more if there are nodes at next level in given perfect binary tree ; create a queue and enqueue left and right children of root ; we process two nodes at a time , so we need two variables to stroe two front items of queue ; traversal loop ; pop two items from queue ; print children of first and second in reverse order ; if first and second have grandchildren , enqueue them in reverse order ; 

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


def printSpecificLevelOrder(root):
    if root is None:
        return
    print(root .data,)
    if root .left is not None:
        print(root .left .data,)
        print(root .right .data,)
    if root .left .left is None:
        return
    q = []
    q .append(root .left)
    q .append(root .right)
    first = None
    second = None
    while (len(q) > 0):
        first = q .pop(0)
        second = q .pop(0)
        print(first .left .data,)
        print(second .right .data,)
        print(first .right .data,)
        print(second .left .data,)
        if first .left .left is not None:
            q .append(first .left)
            q .append(second .right)
            q .append(first .right)
            q .append(second .left)


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(10)
root .left .right .right = Node(11)
root .right .left .left = Node(12)
root .right .left .right = Node(13)
root .right .right .left = Node(14)
root .right .right .right = Node(15)
root .left .left .left .left = Node(16)
root .left .left .left .right = Node(17)
root .left .left .right .left = Node(18)
root .left .left .right .right = Node(19)
root .left .right .left .left = Node(20)
root .left .right .left .right = Node(21)
root .left .right .right .left = Node(22)
root .left .right .right .right = Node(23)
root .right .left .left .left = Node(24)
root .right .left .left .right = Node(25)
root .right .left .right .left = Node(26)
root .right .left .right .right = Node(27)
root .right .right .left .left = Node(28)
root .right .right .left .right = Node(29)
root .right .right .right .left = Node(30)
root .right .right .right .right = Node(31)
print("Specific Level Order traversal of binary tree is")
printSpecificLevelOrder(root)

# Expected output:
Specific Level Order traversal of binary tree is
1
2
3
4
7
5
6
8
15
9
14
10
13
11
12
16
31
17
30
18
29
19
28
20
27
21
26
22
25
23
24
# channel assignment problem | a depth first search based recursive function that returns true if a matching for vertex u is possible ; try every receiver one by one ; if sender u has packets to send to receiver v and receiver v is not already mapped to any other sender just check if the number of packets is greater than '0' because only one packet can be sent in a time frame anyways ; mark v as visited ; if receiver ' v ' is not assigned to any sender or previously assigned sender for receiver v ( which is matchr [ v ] ) has an alternate receiver available . since v is marked as visited in the above line , matchr [ v ] in the following recursive call will not get receiver ' v ' again ; returns maximum number of packets that can be sent parallely in 1 time slot from sender to receiver ; initially all receivers are not mapped to any senders ; count of receivers assigned to senders ; mark all receivers as not seen for next sender ; find if the sender ' u ' can be assigned to the receiver ; 
def bpm(table, u, seen, matchR):
    global M, N
    for v in range(N):
        if (table[u][v] > 0 and not seen[v]):
            seen[v] = True
            if (matchR[v] < 0 or bpm(table, matchR[v], seen, matchR)):
                matchR[v] = u
                return True
    return False


def maxBPM(table):
    global M, N
    matchR = [-1] * N
    result = 0
    for u in range(M):
        seen = [0] * N
        if (bpm(table, u, seen, matchR)):
            result += 1
    print("The number of maximum packets sent", "in the time slot is", result)
    for x in range(N):
        if (matchR[x] + 1 != 0):
            print("T", matchR[x] + 1, "-> R", x + 1)
    return result


M = 3
N = 4
table = [[0, 2, 0], [3, 0, 1], [2, 4, 0]]
max_flow = maxBPM(table)

# Expected output:
The number of maximum packets sent in the time slot is 3
T 3 -> R 1
T 1 -> R 2
T 2 -> R 3
# k centers problem | set 1 ( greedy approximate algorithm ) | python3 program for the above approach ; index of city having the maximum distance to it 's  closest center ; updating the distance of the cities to their closest centers ; updating the index of the city with the maximum distance to it 's closest center ; printing the maximum distance of a city to a center that is our answer print ( ) ; printing the cities that were chosen to be made centers ; 
def maxindex(dist, n):
    mi = 0
    for i in range(n):
        if (dist[i] > dist[mi]):
            mi = i
    return mi


def selectKcities(n, weights, k):
    dist = [0] * n
    centers = []
    for i in range(n):
        dist[i] = 10 ** 9
    max = 0
    for i in range(k):
        centers .append(max)
        for j in range(n):
            dist[j] = min(dist[j], weights[max][j])
        max = maxindex(dist, n)
    print(dist[max])
    for i in centers:
        print(i, end=" ")


if __name__ == '__main__':
    n = 4
    weights = [[0, 4, 8, 5], [4, 0, 10, 7], [8, 10, 0, 9], [5, 7, 9, 0]]
    k = 2
    selectKcities(n, weights, k)

# Expected output:
5
0 2
# hierholzer 's algorithm for directed graph | python3 program to print eulerian circuit in given directed graph using hierholzer algorithm ; adj represents the adjacency list of the directed graph edge_count represents the number of edges emerging from a vertex ; find the count of edges to keep track of unused edges ; empty graph maintain a stack to keep vertices ; vector to store final circuit ; start from any vertex ; current vertex ; if there 's remaining edge ; push the vertex ; find the next vertex using an edge ; and remove that edge ; move to next vertex ; back - track to find remaining circuit ; back - tracking ; we 've got the circuit, now print it in reverse ; 
def printCircuit(adj):
    edge_count = dict()
    for i in range(len(adj)):
        edge_count[i] = len(adj[i])
    if len(adj) == 0:
        return
    curr_path = []
    circuit = []
    curr_path .append(0)
    curr_v = 0
    while len(curr_path):
        if edge_count[curr_v]:
            curr_path .append(curr_v)
            next_v = adj[curr_v][-1]
            edge_count[curr_v] -= 1
            adj[curr_v].pop()
            curr_v = next_v
        else:
            circuit .append(curr_v)
            curr_v = curr_path[-1]
            curr_path .pop()
    for i in range(len(circuit) - 1, -1, -1):
        print(circuit[i], end="")
        if i:
            print(" -> ", end="")


if __name__ == "__main__":
    adj1 = [0] * 3
    for i in range(3):
        adj1[i] = []
    adj1[0].append(1)
    adj1[1].append(2)
    adj1[2].append(0)
    printCircuit(adj1)
    print()
    adj2 = [0] * 7
    for i in range(7):
        adj2[i] = []
    adj2[0].append(1)
    adj2[0].append(6)
    adj2[1].append(2)
    adj2[2].append(0)
    adj2[2].append(3)
    adj2[3].append(4)
    adj2[4].append(2)
    adj2[4].append(5)
    adj2[5].append(0)
    adj2[6].append(4)
    printCircuit(adj2)
    print()

# Expected output:
0 -> 1 -> 2 -> 0
0 -> 6 -> 4 -> 5 -> 0 -> 1 -> 2 -> 3 -> 4 -> 2 -> 0
# perfect binary tree specific level order traversal | set 2 | linked list node ; given a perfect binary tree , print its nodes in specific level order ; for level order traversal ; stack to print reverse ; vector to store the level ; considering size of the level ; push data of the node of a particular level to vector ; push vector containing a level in stack ; print the stack ; finally pop all nodes from stack and prints them . ; finally print root ; 

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


def specific_level_order_traversal(root):
    q = []
    s = []
    q .append(root)
    sz = 0
    while (len(q) > 0):
        v = []
        sz = len(q)
        i = 0
        while (i < sz):
            temp = q[0]
            q .pop(0)
            v .append(temp .data)
            if (temp .left is not None):
                q .append(temp .left)
            if (temp .right is not None):
                q .append(temp .right)
            i = i + 1
        s .append(v)
    while (len(s) > 0):
        v = s[-1]
        s .pop()
        i = 0
        j = len(v) - 1
        while (i < j):
            print(v[i], " ", v[j], end=" ")
            j = j - 1
            i = i + 1
    print(root .data)


root = Node(1)
root .left = Node(2)
root .right = Node(3)
print("Specific Level Order traversal of binary tree is")
specific_level_order_traversal(root)

# Expected output:
Specific Level Order traversal of binary tree is
2   3 1