giulio98/xlcost-single-prompt huggingface dataset:
# shortest path to reach one prime to other by changing single digit at a time | python3 program to reach a prime number from another by changing single digits and using only prime numbers . ; finding all 4 digit prime numbers ; create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . a value in prime [ i ] will finally be false if i is not a prime , else true . ; if prime [ p ] is not changed , then it is a prime ; update all multiples of p ; forming a vector of prime numbers ; in1 and in2 are two vertices of graph which are actually indexes in pset [ ] ; returns true if num1 and num2 differ by single digit . ; to compare the digits ; if the numbers differ only by a single digit return true else false ; generate all 4 digit ; create a graph where node numbers are indexes in pset [ ] and there is an edge between two nodes only if they differ by single digit . ; since graph nodes represent indexes of numbers in pset [ ] , we find indexes of num1 and num2 . ; 

import queue


class Graph:

    def __init__(self, V):
        self.V = V
        self.l = [[] for i in range(V)]

    def addedge(self, V1, V2):
        self.l[V1].append(V2)
        self.l[V2].append(V1)

    def bfs(self, in1, in2):
        visited = [0] * self.V
        que = queue.Queue()
        visited[in1] = 1
        que.put(in1)
        while (not que.empty()):
            p = que.queue[0]
            que.get()
            i = 0
            while i < len(self.l[p]):
                if (not visited[self.l[p][i]]):
                    visited[self.l[p][i]] = visited[p] + 1
                    que.put(self.l[p][i])
                if (self.l[p][i] == in2):
                    return visited[self.l[p][i]] - 1
                i += 1


def SieveOfEratosthenes(v):
    n = 9999
    prime = [True] * (n + 1)

    p = 2
    while p * p <= n:
        if (prime[p] == True):
            for i in range(p * p, n + 1, p):
                prime[i] = False
        p += 1
    for p in range(1000, n + 1):
        if (prime[p]):
            v.append(p)


def compare(num1, num2):
    s1 = str(num1)
    s2 = str(num2)
    c = 0
    if (s1[0] != s2[0]):
        c += 1
    if (s1[1] != s2[1]):
        c += 1
    if (s1[2] != s2[2]):
        c += 1
    if (s1[3] != s2[3]):
        c += 1
    return (c == 1)


def shortestPath(num1, num2):
    pset = []
    SieveOfEratosthenes(pset)
    g = Graph(len(pset))
    for i in range(len(pset)):
        for j in range(i + 1, len(pset)):
            if (compare(pset[i], pset[j])):
                g.addedge(i, j)
    in1, in2 = None, None
    for j in range(len(pset)):
        if (pset[j] == num1):
            in1 = j
    for j in range(len(pset)):
        if (pset[j] == num2):
            in2 = j

    return g.bfs(in1, in2)


if __name__ == '__main__':
    num1 = 1033
    num2 = 8179
    print(shortestPath(num1, num2))

# Expected output:
6
# level of each node in a tree from source node ( using bfs ) | python3 program to determine level of each node and print level ; function to determine level of each node starting from x using bfs ; array to store level of each node ; create a queue ; enqueue element x ; initialize level of source node to 0 ; marked it as visited ; do until queue is empty ; get the first element of queue ; traverse neighbors of node x ; b is neighbor of node x ; if b is not marked already ; enqueue b in queue ; level of b is level of x + 1 ; mark b ; display all nodes and their levels ; 

import queue


def printLevels(graph, V, x):
    level = [None] * V
    marked = [False] * V
    que = queue .Queue()
    que .put(x)
    level[x] = 0
    marked[x] = True
    while (not que .empty()):
        x = que .get()
        for i in range(len(graph[x])):
            b = graph[x][i]
            if (not marked[b]):
                que .put(b)
                level[b] = level[x] + 1
                marked[b] = True
    print("Nodes", " ", "Level")
    for i in range(V):
        print(" ", i, " --> ", level[i])


if __name__ == '__main__':
    V = 8
    graph = [[]for i in range(V)]
    graph[0].append(1)
    graph[0].append(2)
    graph[1].append(3)
    graph[1].append(4)
    graph[1].append(5)
    graph[2].append(5)
    graph[2].append(6)
    graph[6].append(7)
    printLevels(graph, V, 0)

# Expected output:
Nodes   Level
  0  -->  0
  1  -->  1
  2  -->  1
  3  -->  2
  4  -->  2
  5  -->  2
  6  -->  2
  7  -->  3
# construct binary palindrome by repeated appending and trimming | function to apply dfs ; set the parent marked ; if the node has not been visited set it and its children marked ; link which digits must be equal ; connect the two indices ; set everything connected to first character as 1 ; 
def dfs(parent, ans, connectchars):
    ans[parent] = 1
    for i in range(len(connectchars[parent])):
        if (not ans[connectchars[parent][i]]):
            dfs(connectchars[parent][i], ans, connectchars)


def printBinaryPalindrome(n, k):
    arr = [0] * n
    ans = [0] * n
    connectchars = [[]for i in range(k)]
    for i in range(n):
        arr[i] = i % k
    for i in range(int(n / 2)):
        connectchars[arr[i]].append(arr[n - i - 1])
        connectchars[arr[n - i - 1]].append(arr[i])
    dfs(0, ans, connectchars)
    for i in range(n):
        print(ans[arr[i]], end="")


if __name__ == '__main__':
    n = 10
    k = 4
    printBinaryPalindrome(n, k)

# Expected output:
1100110011
# dfs for a n | dfs on tree ; printing traversed node ; traversing adjacent edges ; not traversing the parent node ; 
def dfs(List, node, arrival):
    print(node)
    for i in range(len(List[node])):
        if (List[node][i] != arrival):
            dfs(List, List[node][i], node)


if __name__ == '__main__':
    nodes = 5
    List = [[]for i in range(10000)]
    List[1].append(2)
    List[2].append(1)
    List[1].append(3)
    List[3].append(1)
    List[2].append(4)
    List[4].append(2)
    List[3].append(5)
    List[5].append(3)
    dfs(List, 1, 0)

# Expected output:
1
2
4
3
5
# maximum number of edges to be added to a tree so that it stays a bipartite graph | to store counts of nodes with two colors ; increment count of nodes with current color ; traversing adjacent nodes ; not recurring for the parent node ; finds maximum number of edges that can be added without violating bipartite property . ; do a dfs to count number of nodes of each color ; 
def dfs(adj, node, parent, color):
    count_color[color] += 1
    for i in range(len(adj[node])):
        if (adj[node][i] != parent):
            dfs(adj, adj[node][i], node, not color)


def findMaxEdges(adj, n):
    dfs(adj, 1, 0, 0)
    return (count_color[0] * count_color[1] - (n - 1))


count_color = [0, 0]
n = 5
adj = [[]for i in range(n + 1)]
adj[1].append(2)
adj[1].append(3)
adj[2].append(4)
adj[3].append(5)
print(findMaxEdges(adj, n))

# Expected output:
2
# min steps to empty an array by removing a pair each time with sum at most k | function to count minimum steps ; function to sort the array ; run while loop ; condition to check whether sum exceed the target or not ; increment the step by 1 ; return minimum steps ; given array arr [ ] ; 
def countMinSteps(arr, target, n):
    arr .sort()
    minimumSteps = 0
    i, j = 0, n - 1
    while i <= j:
        if arr[i] + arr[j] <= target:
            i += 1
            j -= 1
        else:
            j -= 1
        minimumSteps += 1
    return minimumSteps


arr = [4, 6, 2, 9, 6, 5, 8, 10]
target = 11
size = len(arr)
print(countMinSteps(arr, target, size))

# Expected output:
5
# sort the strings based on the numbers of matchsticks required to represent them | stick [ ] stores the count of sticks required to represent the alphabets ; number [ ] stores the count of sticks required to represent the numerals ; function that return the count of sticks required to represent the given string str ; loop to iterate over every character of the string ; add the count of sticks required to represent the current character ; function to sort the array according to the number of sticks required to represent it ; vector to store the number of sticks required with respective strings ; inserting number of sticks with respective strings ; sort the vector ; print the sorted vector ; 

sticks = [6, 7, 4, 6, 5, 4, 6, 5, 2, 4, 4, 3,
          6, 6, 6, 5, 7, 6, 5, 3, 5, 4, 6, 4, 3, 4]
number = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]


def countSticks(st):
    cnt = 0
    for i in range(len(st)):
        ch = st[i]
        if (ch >= 'A' and ch <= 'Z'):
            cnt += sticks[ord(ch) - ord('A')]
        else:
            cnt += number[ord(ch) - ord('0')]
    return cnt


def sortArr(arr, n):
    vp = []
    for i in range(n):
        vp .append([countSticks(arr[i]), arr[i]])
    vp .sort()
    for i in range(len(vp)):
        print(vp[i][1], end=" ")


if __name__ == "__main__":
    arr = ["GEEKS", "FOR", "GEEKSFORGEEKS"]
    n = len(arr)
    sortArr(arr, n)

# Expected output:
FOR GEEKS GEEKSFORGEEKS
# count number of pairs with positive sum in an array | returns number of pairs in arr [ 0. . n - 1 ] with positive sum ; initialize result ; consider all possible pairs and check their sums ; if arr [ i ] & arr [ j ] form valid pair ; 
def CountPairs(arr, n):
    count = 0
    for i in range(n):
        for j in range(i + 1, n):
            if (arr[i] + arr[j] > 0):
                count += 1
    return count


if __name__ == "__main__":
    arr = [-7, -1, 3, 2]
    n = len(arr)
    print(CountPairs(arr, n))

# Expected output:
3
# find if there exists a direction for ranges such that no two range intersect | python implementation of the approach ; function that returns true if the assignment of directions is possible ; structure to hold details of each interval ; sort the intervals based on velocity ; test the condition for all intervals with same velocity ; if for any velocity , 3 or more intervals share a common poreturn false ; 

MAX = 100001


def isPossible(rangee, N):
    test = [[0 for x in range(3)]for x in range(N)]
    for i in range(N):
        test[i][0] = rangee[i][0]
        test[i][1] = rangee[i][1]
        test[i][2] = rangee[i][2]
    test .sort(key=lambda x: x[2])
    for i in range(N):
        count = [0] * MAX
        current_velocity = test[i][2]
        j = i
        while (j < N and test[j][2] == current_velocity):
            for k in range(test[j][0], test[j][1] + 1):
                count[k] += 1
                if (count[k] >= 3):
                    return False
            j += 1
        i = j - 1
    return True


rangee = [[1, 2, 3], [2, 5, 1], [3, 10, 1], [4, 4, 1], [5, 7, 10]]
n = len(rangee)
if (isPossible(rangee, n)):
    print("Yes")
else:
    print("No")

# Expected output:
No
# a | function to return the modified string ; to store the previous character ; to store the starting indices of all the groups ; starting index of the first group ; if the current character and the previous character differ ; push the starting index of the new group ; the current character now becomes previous ; sort the first group ; sort all the remaining groups ; print ( ''.join(st)) ; return the modified string ; 
def get_string(st, n):
    prev = st[0]
    result = []
    result .append(0)
    for i in range(1, n):
        if (st[i].isdigit() != prev .isdigit()):
            result .append(i)
        prev = st[i]
    st = list(st)
    st[:result[0]].sort()
    p = st .copy()
    for i in range(len(result) - 1):
        p[result[i]:result[i + 1]] = sorted(st[result[i]:result[i + 1]])
    p[len(p) - 2:] = sorted(st[result[-1]:])
    return ''.join(p)


if __name__ == "__main__":
    st = "121geeks21"
    n = len(st)
    print(get_string(st, n))

# Expected output:
112eegks12
# find the kth smallest number with sum of digits as m | python3 implementation of the approach ; recursively moving to add all the numbers upto a limit with sum of digits as m ; max nber of digits allowed in a nber for this implementation ; function to return the kth number with sum of digits as m ; the kth smallest number is found ; 

N = 2005
ans = dict()


def dfs(n, left, ct):
    if (ct >= 15):
        return
    if (left == 0):
        ans[n] = 1
    for i in range(min(left, 9) + 1):
        dfs(n * 10 + i, left - i, ct + 1)


def getKthNum(m, k):
    dfs(0, m, 0)
    c = 0
    for it in sorted(ans .keys()):
        c += 1
        if (c == k):
            return it
    return -1


m = 5
k = 3
print(getKthNum(m, k))

# Expected output:
23
# remove minimum elements from the array such that 2 * min becomes more than max | python3 program to remove minimum elements from the array such that 2 * min becomes more than max ; function to remove minimum elements from the array such that 2 * min becomes more than max ; sort the array ; to store the required answer ; traverse from left to right ; update the answer ; return the required answer ; 

from bisect import bisect_left as upper_bound


def Removal(v, n):
    v = sorted(v)
    ans = 10 ** 9
    for i in range(len(v)):
        j = upper_bound(v, (2 * (a[i])))
        ans = min(ans, n - (j - i - 1))
    return ans


a = [4, 5, 100, 9, 10, 11, 12, 15, 200]
n = len(a)
print(Removal(a, n))

# Expected output:
4
# sort the queue using recursion | defining a class queue ; function to push element in last by popping from front until size becomes 0 ; base condition ; pop front element and push this last in a queue ; recursive call for pushing element ; function to push an element in the queue while maintaining the sorted order ; base condition ; if current element is less than the element at the front ; call stack with front of queue ; recursive call for inserting a front element of the queue to the last ; push front element into last in a queue ; recursive call for pushing element in a queue ; function to sort the given queue using recursion ; return if queue is empty ; get the front element which will be stored in this variable throughout the recursion stack ; recursive call ; push the current element into the queue according to the sorting order ; 

class Queue:
    def __init__(self):
        self .queue = []

    def put(self, item):
        self .queue .append(item)

    def get(self):
        if len(self .queue) < 1:
            return None
        return self .queue .pop(0)

    def front(self):
        return self .queue[0]

    def size(self):
        return len(self .queue)

    def empty(self):
        return not (len(self .queue))


def FrontToLast(q, qsize):
    if qsize <= 0:
        return
    q .put(q .get())
    FrontToLast(q, qsize - 1)


def pushInQueue(q, temp, qsize):
    if q .empty() or qsize == 0:
        q .put(temp)
        return
    elif temp <= q .front():
        q .put(temp)
        FrontToLast(q, qsize)
    else:
        q .put(q .get())
        pushInQueue(q, temp, qsize - 1)


def sortQueue(q):
    if q .empty():
        return
    temp = q .get()
    sortQueue(q)
    pushInQueue(q, temp, q .size())


qu = Queue()
qu .put(10)
qu .put(7)
qu .put(16)
qu .put(9)
qu .put(20)
qu .put(5)
sortQueue(qu)
while not qu .empty():
    print(qu .get(), end=' ')

# Expected output:
5 7 9 10 16 20
# find original numbers from gcd ( ) every pair | python 3 implementation of the approach ; utility function to print the contents of an array ; function to find the required numbers ; sort array in decreasing order ; count frequency of each element ; size of the resultant array ; store the highest element in the resultant array ; decrement the frequency of that element ; compute gcd ; decrement gcd value by 2 ;  ; 

from math import sqrt, gcd


def printArr(arr, n):
    for i in range(n):
        print(arr[i], end=" ")


def findNumbers(arr, n):
    arr .sort(reverse=True)
    freq = [0 for i in range(arr[0] + 1)]
    for i in range(n):
        freq[arr[i]] += 1
    size = int(sqrt(n))
    brr = [0 for i in range(len(arr))]
    l = 0
    for i in range(n):
        if (freq[arr[i]] > 0):
            brr[l] = arr[i]
            freq[brr[l]] -= 1
            l += 1
            for j in range(l):
                if (i != j):
                    x = gcd(arr[i], brr[j])
                    freq[x] -= 2
    printArr(brr, size)


if __name__ == '__main__':
    arr = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
           1, 1, 1, 1, 1, 5, 5, 5, 7, 10, 12, 2, 2]
    n = len(arr)
    findNumbers(arr, n)

# Expected output:
12 10 7 5 1
# bitwise and of n binary strings | python3 implementation of the above approach ; function to find the bitwise and of all the binary strings ; to store the largest and the smallest string ' s ▁ size , ▁ we ▁ need ▁ this ▁ to ▁ add ▁ ' 0 's  in the resultant string ; reverse each string since we need to perform and operation on bits from right to left ; update the respective length values ; traverse bits from 0 to smallest string 's size ; if at this bit position , there is a 0 in any of the given strings then and operation on current bit position will be 0 ; add resultant bit to result ; add 0 's to the string. ; reverse the string since we started from left to right ; return the resultant string ; 

import sys


def strBitwiseAND(arr, n):
    res = ""
    smallest_size = sys .maxsize
    largest_size = -(sys .maxsize - 1)
    for i in range(n):
        arr[i] = arr[i][::-1]
        smallest_size = min(smallest_size, len(arr[i]))
        largest_size = max(largest_size, len(arr[i]))
    for i in range(smallest_size):
        all_ones = True
        for j in range(n):
            if (arr[j][i] == '0'):
                all_ones = False
                break
        if all_ones:
            res += '1'
        else:
            res += '0'
    for i in range(largest_size - smallest_size):
        res += '0'
    res = res[::-1]
    return res


if __name__ == "__main__":
    arr = ["101", "110110", "111"]
    n = len(arr)
    print(strBitwiseAND(arr, n))

# Expected output:
000100
# print all paths from a given source to a destination using bfs | python3 program to print all paths of source to destination in given graph ; utility function for printing the found path in graph ; utility function to check if current vertex is already present in path ; utility function for finding paths in graph from source to destination ; create a queue which stores the paths ; path vector to store the current path ; if last vertex is the desired destination then print the path ; traverse to all the nodes connected to current vertex and push new path to queue ; 

from typing import List
from collections import deque


def printpath(path: List[int]) -> None:
    size = len(path)
    for i in range(size):
        print(path[i], end=" ")
    print()


def isNotVisited(x: int, path: List[int]) -> int:
    size = len(path)
    for i in range(size):
        if (path[i] == x):
            return 0
    return 1


def findpaths(g: List[List[int]], src: int, dst: int, v: int) -> None:
    q = deque()
    path = []
    path .append(src)
    q .append(path .copy())
    while q:
        path = q .popleft()
        last = path[len(path) - 1]
        if (last == dst):
            printpath(path)
        for i in range(len(g[last])):
            if (isNotVisited(g[last][i], path)):
                newpath = path .copy()
                newpath .append(g[last][i])
                q .append(newpath)


if __name__ == "__main__":
    v = 4
    g = [[]for _ in range(4)]
    g[0].append(3)
    g[0].append(1)
    g[0].append(2)
    g[1].append(3)
    g[2].append(0)
    g[2].append(1)
    src = 2
    dst = 3
    print("path from src {} to dst {} are".format(src, dst))
    findpaths(g, src, dst, v)

# Expected output:
path from src 2 to dst 3 are
2 0 3 
2 1 3 
2 0 1 3
# rearrange odd and even values in alternate fashion in ascending order | python3 implementation of the above approach ; sort the array ; v1 = list ( ) to insert even values v2 = list ( ) to insert odd values ; set flag to true if first element is even ; start rearranging array ; if first element is even ; else , first element is odd ; print the rearranged array ; 
def AlternateRearrange(arr, n):

    arr.sort()

    v1 = list()
    v2 = list()

    for i in range(n):
        if (arr[i] % 2 == 0):
            v1.append(arr[i])
        else:
            v2.append(arr[i])

    index = 0
    i = 0
    j = 0

    flag = False

    if (arr[0] % 2 == 0):
        flag = True

    while (index < n):
        if (flag == True and i < len(v1)):
            arr[index] = v1[i]
            index += 1
            i += 1
            flag = ~flag
        elif j < len(v2):
            arr[index] = v2[j]
            index += 1
            j += 1

            flag = ~flag

    for i in range(n):
        print(arr[i], end=" ")


arr = [9, 8, 13, 2, 19, 14, 21, 23, 25]
n = len(arr)

AlternateRearrange(arr, n)

# Expected output:
2 9 8 13 14 19 21 23 25
# convert given array to arithmetic progression by adding an element | function to return the number to be added ; if difference of the current consecutive elements is different from the common difference ; if number has already been chosen then it 's not possible to add  another number ; if the current different is twice the common difference then a number can be added midway from current and previous element ; number has been chosen ; it 's not possible to maintain  the common difference ; return last element + common difference if no element is chosen and the array is already in ap ; else return the chosen number ; 
def getNumToAdd(arr, n):
    arr .sort(reverse=False)
    d = arr[1] - arr[0]
    numToAdd = -1
    numAdded = False
    for i in range(2, n, 1):
        diff = arr[i] - arr[i - 1]
        if (diff != d):
            if (numAdded):
                return -1
            if (diff == 2 * d):
                numToAdd = arr[i] - d
                numAdded = True
            else:
                return -1
    if (numToAdd == -1):
        return (arr[n - 1] + d)
    return numToAdd


if __name__ == '__main__':
    arr = [1, 3, 5, 7, 11, 13, 15]
    n = len(arr)
    print(getNumToAdd(arr, n))

# Expected output:
9
# minimum numbers of cells that are connected with the smallest path between 3 given cells | function to return the minimum cells that are connected via the minimum length path ; array to store column number of the given cells ; sort cells in ascending order of row number ; middle row number ; set pair to store required cells ; range of column number ; store all cells of middle row within column number range ; final step to store all the column number of 1 st and 3 rd cell upto midrow ; 
def Minimum_Cells(v):
    col = [0] * 3
    for i in range(3):
        column_number = v[i][1]
        col[i] = column_number
    col .sort()
    v .sort()
    MidRow = v[1][0]
    s = set()
    Maxcol = col[2]
    MinCol = col[0]
    for i in range(MinCol, int(Maxcol) + 1):
        s .add((MidRow, i))
    for i in range(3):
        if (v[i][0] == MidRow):
            continue
        for j in range(min(v[i][0], MidRow), max(v[i][0], MidRow) + 1):
            s .add((j, v[i][1]))
    return len(s)


if __name__ == "__main__":
    v = [(0, 0), (1, 1), (2, 2)]
    print(Minimum_Cells(v))

# Expected output:
5
# Get maximum items when other items of total cost of an item are free | Function to count the total number of items ; Sort the prices ; Choose the last element ; Initial count of item ; Sum to keep track of the total price of free items ; If total is less than or equal to z then we will add 1 to the answer ;
def items(n, a):
    a .sort()
    z = a[n - 1]
    x = 1
    s = 0
    for i in range(0, n - 1):
        s += a[i]
        if (s <= z):
            x += 1
        else:
            break
    return x


n = 5
a = [5, 3, 1, 5, 6]
print(items(n, a))

# Expected output:
3