giulio98/xlcost-single-prompt huggingface dataset:
# remove duplicates from a given string | python3 program to remove duplicate character from character array and prin sorted order ; used as index in the modified string ; traverse through all characters ; check if str [ i ] is present before it ; if not present , then add it to result . ; 
def removeDuplicate(str, n):
    index = 0
    for i in range(0, n):
        for j in range(0, i + 1):
            if (str[i] == str[j]):
                break
        if (j == i):
            str[index] = str[i]
            index += 1
    return "".join(str[:index])


str = "geeksforgeeks"
n = len(str)
print(removeDuplicate(list(str), n))

# Expected output:
geksfor
# check if it ’ s possible to completely fill every container with same ball | a boolean function that returns true if it 's possible to completely fill the container else return false ; base case ; backtracking ; function to check the conditions ; storing frequencies ; function call for backtracking ; 
def getans(i, v, q):
    if (i == len(q)):
        return True
    for j in range(len(v)):
        if (v[j] >= q[i]):
            v[j] -= q[i]
            if (getans(i + 1, v, q)):
                return True
            v[j] += q[i]
    return False


def Check(c, b):
    m = {}
    for i in range(len(b)):
        if b[i] in m:
            m[b[i]] += 1
        else:
            m[b[i]] = 1
    v = []
    for key, value in m .items():
        v .append(value)
    check = getans(0, v, c)
    if (check):
        print("YES")
    else:
        print("NO")


if __name__ == '__main__':
    c = [1, 3, 3]
    b = [2, 2, 2, 2, 4, 4, 4]
    Check(c, b)

# Expected output:
YES
# maximum bitwise xor of node values of an acyclic graph made up of n given vertices using m edges | function to find the maximum bitwise xor of any subset of the array of size k ; number of node must k + 1 for k edges ; stores the maximum bitwise xor ; generate all subsets of the array ; __builtin_popcount ( ) returns the number of sets bits in an integer ; initialize current xor as 0 ; if jth bit is set in i then include jth element in the current xor ; update the maximum bitwise xor obtained so far ; return the maximum xor ; 
def maximumXOR(arr, n, K):
    K += 1
    maxXor = -10 ** 9
    for i in range(1 << n):
        if (bin(i).count('1') == K):
            cur_xor = 0
            for j in range(n):
                if (i & (1 << j)):
                    cur_xor = cur_xor ^ arr[j]
            maxXor = max(maxXor, cur_xor)
    return maxXor


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

# Expected output:
7
# tower of hanoi | set 2 | python program for the above approach ; function to print order of movement of n disks across three rods to place all disks on the third rod from the first - rod using binary representation ; iterate over the range [ 0 , 2 ^ n - 1 ] ; print the movement of the current rod ; 

import math


def TowerOfHanoi(N):
    for x in range(1, int(math .pow(2, N))):
        print("Move from Rod ", ((x & x - 1) % 3 + 1),
              " to Rod ", (((x | x - 1) + 1) % 3 + 1))


N = 3
TowerOfHanoi(N)

# Expected output:
Move from Rod  1  to Rod  3
Move from Rod  1  to Rod  2
Move from Rod  3  to Rod  2
Move from Rod  1  to Rod  3
Move from Rod  2  to Rod  1
Move from Rod  2  to Rod  3
Move from Rod  1  to Rod  3
# check if a path exists from a given cell to any boundary element of the matrix with sum of elements not exceeding k | python3 program for the above approach ; function to check if it is valid to move to the given index or not ; otherwise return false ; function to check if there exists a path from the cell ( x , y ) of the matrix to any boundary cell with sum of elements at most k or not ; base case ; if k >= board [ x ] [ y ] ; stores the current element ; mark the current cell as visited ; visit all the adjacent cells ; mark the cell unvisited ; return false ; 

import sys
INT_MAX = sys .maxsize


def isValid(board, i, j, K):
    if (board[i][j] <= K):
        return True
    return False


def findPath(board, X, Y, M, N, K):
    if (X < 0 or X == M or Y < 0 or Y == N):
        return True
    if (isValid(board, X, Y, K)):
        board_XY = board[X][Y]
        board[X][Y] = INT_MAX
        if (findPath(board, X +
                     1, Y, M, N, K -
                     board_XY) or findPath(board, X -
                                           1, Y, M, N, K -
                                           board_XY) or findPath(board, X, Y +
                                                                 1, M, N, K -
                                                                 board_XY) or findPath(board, X, Y -
                                                                                       1, M, N, K -
                                                                                       board_XY)):
            return True
        board[X][Y] = board_XY
    return False


if __name__ == "__main__":
    grid = [
        [
            25, 5, 25, 25, 25, 25], [
            25, 1, 1, 5, 12, 25], [
                25, 1, 12, 0, 15, 25], [
                    22, 1, 11, 2, 19, 15], [
                        25, 2, 2, 1, 12, 15], [
                            25, 9, 10, 1, 11, 25], [
                                25, 25, 25, 25, 25, 25]]
    K = 17
    M = len(grid)
    N = len(grid[0])
    X = 2
    Y = 3
    if (findPath(grid, X, Y, M, N, K)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# sum of all subsets whose sum is a perfect number from a given array | function to check is a given number is a perfect number or not ; stores sum of divisors ; add all divisors of x to sum_div ; if the sum of divisors is equal to the given number , return true ; otherwise , return false ; function to find the sum of all the subsets from an array whose sum is a perfect number ; stores the total number of subsets , i . e . 2 ^ n ; consider all numbers from 0 to 2 ^ n - 1 ; consider array elements from positions of set bits in the binary representation of n ; if sum of chosen elements is a perfect number ; 
def isPerfect(x):
    sum_div = 1
    for i in range(2, int(x / 2 + 1)):
        if (x % i == 0):
            sum_div = sum_div + i
    if (sum_div == x):
        return 1
    else:
        return 0


def subsetSum(arr, n):
    total = 1 << n
    for i in range(total):
        sum = 0
        for j in range(n):
            if (i & (1 << j) != 0):
                sum = sum + arr[j]
        if (isPerfect(sum)):
            print(sum, " ")


arr = [5, 4, 6]
N = len(arr)
subsetSum(arr, N)

# Expected output:
6
# pen distribution problem | recursive function to play game ; box is empty , game over ! or both have quit , game over ! ; p1 moves ; p2 moves ; increment x ; switch moves between p1 and p2 ; function to find the number of pens remaining in the box and calculate score for each player ; score of p1 ; score of p2 ; initialized to zero ; move = 0 , p1 ' s ▁ turn ▁ ▁ move ▁ = ▁ 1 , ▁ p2' s turn ; has p1 quit ; has p2 quit ; recursively continue the game ; 
def solve(N, P1, P2, X, Move, QuitP1, QuitP2):
    if (N == 0 or (QuitP1 and QuitP2)):
        print("Number of pens remaining in the box: ", N)
        print("Number of pens collected by P1: ", P1)
        print("Number of pens collected by P2: ", P2)
        return
    if (Move == 0 and QuitP1 == False):
        req_P1 = int(pow(2, X))
        if (req_P1 <= N):
            P1 += req_P1
            N -= req_P1
        else:
            QuitP1 = True
    elif (Move == 1 and QuitP2 == False):
        req_P2 = int(pow(3, X))
        if (req_P2 <= N):
            P2 += req_P2
            N -= req_P2
        else:
            QuitP2 = True
    X += 1
    if (Move == 1):
        Move = 0
    else:
        Move = 1
    solve(N, P1, P2, X, Move, QuitP1, QuitP2)


def PenGame(N):
    P1 = 0
    P2 = 0
    X = 0
    Move = False
    QuitP1 = False
    QuitP2 = False
    solve(N, P1, P2, X, Move, QuitP1, QuitP2)


N = 22
PenGame(N)

# Expected output:
Number of pens remaining in the box:  14
Number of pens collected by P1:  5
Number of pens collected by P2:  3
# minimum cost path in a directed graph via given set of intermediate nodes | stores minimum - cost of path from source ; function to perform bfs on graph g starting from vertex v ; if destination is reached ; set flag to true ; visit all the intermediate nodes ; if any intermediate node is not visited ; if all intermediate nodes are visited ; update the minsum ; mark the current node visited ; traverse adjacent nodes ; mark the neighbour visited ; find minimum cost path considering the neighbour as the source ; mark the neighbour unvisited ; mark the source unvisited ; 

minSum = 1000000000


def getMinPathSum(graph, visited, necessary, src, dest, currSum):
    global minSum
    if (src == dest):
        flag = True
        for i in necessary:
            if (not visited[i]):
                flag = False
                break
        if (flag):
            minSum = min(minSum, currSum)
        return
    else:
        visited[src] = True
        for node in graph[src]:
            if not visited[node[0]]:
                visited[node[0]] = True
                getMinPathSum(
                    graph,
                    visited,
                    necessary,
                    node[0],
                    dest,
                    currSum +
                    node[1])
                visited[node[0]] = False
        visited[src] = False


if __name__ == '__main__':
    graph = dict()
    graph[0] = [[1, 2], [2, 3], [3, 2]]
    graph[1] = [[4, 4], [0, 1]]
    graph[2] = [[4, 5], [5, 6]]
    graph[3] = [[5, 7], [0, 1]]
    graph[4] = [[6, 4]]
    graph[5] = [[6, 2]]
    graph[6] = [[7, 11]]
    n = 7
    source = 0
    dest = 6
    visited = [False for i in range(n + 1)]
    necessary = [2, 4]
    getMinPathSum(graph, visited, necessary, source, dest, 0)
    if (minSum == 1000000000):
        print(-1)
    else:
        print(minSum)

# Expected output:
12
# unique subsequences of length k with given sum | function to find all the subsequences of a given length and having sum s ; termination condition ; add value to sum ; check if the resultant sum equals to target sum ; if true ; print resultant array ; end this recursion stack ; check all the combinations using backtracking ; check all the combinations using backtracking ; 
def comb(arr, Len, r, ipos, op, opos, Sum):
    if (opos == r):
        sum2 = 0
        for i in range(opos):
            sum2 = sum2 + op[i]
        if (Sum == sum2):
            for i in range(opos):
                print(op[i], end=", ")
            print()
        return
    if (ipos < Len):
        comb(arr, Len, r, ipos + 1, op, opos, Sum)
        op[opos] = arr[ipos]
        comb(arr, Len, r, ipos + 1, op, opos + 1, Sum)


if __name__ == '__main__':
    arr = [4, 6, 8, 2, 12]
    K = 3
    S = 20
    N = len(arr)
    op = [0] * N
    comb(arr, N, K, 0, op, 0, S)

# Expected output:
6, 2, 12,
# traverse the matrix in diagonally bottum | static variable for changing row and column ; flag variable for handling bottum up diagonal traversing ; recursive function to traverse the matrix diagonally bottom - up ; base condition ; condition when to traverse bottom diagonal of the matrix ; print matrix cell value ; recursive function to traverse the matrix diagonally ; recursive function to change diagonal ; 

k1 = 0
k2 = 0
flag = True


def traverseMatrixDiagonally(m, i, j, row, col):
    global k1
    global k2
    global flag
    if (i >= row or j >= col):
        if (flag):
            a = k1
            k1 = k2
            k2 = a
            if (flag):
                flag = False
            else:
                flag = True
            k1 += 1
        else:
            a = k1
            k1 = k2
            k2 = a
            if (flag):
                flag = False
            else:
                flag = True
        print()
        return False
    print(m[i][j], end=" ")
    if (traverseMatrixDiagonally(m, i + 1, j + 1, row, col)):
        return True
    if (traverseMatrixDiagonally(m, k1, k2, row, col)):
        return True
    return True


mtrx = [[10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [
    20, 21, 22, 23, 24], [25, 26, 27, 28, 29], [30, 31, 32, 33, 34]]
traverseMatrixDiagonally(mtrx, 0, 0, 5, 5)

# Expected output:
10 16 22 28 34 
15 21 27 33 
11 17 23 29 
20 26 32 
12 18 24 
25 31 
13 19 
30 
14
# minimum colors required such that edges forming cycle do not have same color | python3 implementation to find the minimum colors required to such that edges forming cycle don 't have same color ; variable to store the graph ; to store that the vertex is visited or not ; boolean value to store that graph contains cycle or not ; variable to store the color of the edges of the graph ; function to traverse graph using dfs traversal ; loop to iterate for all edges from the source vertex ; if the vertex is not visited ; condition to check cross and forward edges of the graph ; presence of back edge ; 

n = 5
m = 7
g = [[]for i in range(m)]
col = [0 for i in range(n)]
cyc = True
res = [0 for i in range(m)]


def dfs(v):
    col[v] = 1
    for p in g[v]:
        to = p[0]
        id = p[1]
        if (col[to] == 0):
            dfs(to)
            res[id] = 1
        elif (col[to] == 2):
            res[id] = 1
        else:
            res[id] = 2
            cyc = True
    col[v] = 2


if __name__ == '__main__':
    g[0].append([1, 0])
    g[0].append([2, 1])
    g[1].append([2, 2])
    g[1].append([3, 3])
    g[2].append([3, 4])
    g[3].append([4, 5])
    g[4].append([2, 6])
    for i in range(n):
        if (col[i] == 0):
            dfs(i)
    print(2 if cyc else 1)
    for i in range(m):
        print(res[i], end=' ')

# Expected output:
2
1 1 1 1 1 1 2
# perfect sum problem | function to print the subsets whose sum is equal to the given target k ; create the new array with size equal to array set [ ] to create binary array as per n ( decimal number ) ; convert the array into binary array ; calculate the sum of this subset ; check whether sum is equal to target if it is equal , then print the subset ; function to find the subsets with sum k ; calculate the total no . of subsets ; run loop till total no . of subsets and call the function for each subset ; 
def sumSubsets(sets, n, target):
    x = [0] * len(sets)
    j = len(sets) - 1
    while (n > 0):
        x[j] = n % 2
        n = n // 2
        j -= 1
    sum = 0
    for i in range(len(sets)):
        if (x[i] == 1):
            sum += sets[i]
    if (sum == target):
        print("{", end="")
        for i in range(len(sets)):
            if (x[i] == 1):
                print(sets[i], end=", ")
        print("}, ", end="")


def findSubsets(arr, K):
    x = pow(2, len(arr))
    for i in range(1, x):
        sumSubsets(arr, i, K)


if __name__ == "__main__":
    arr = [5, 10, 12, 13, 15, 18]
    K = 30
    findSubsets(arr, K)

# Expected output:
{12, 18, }, {5, 12, 13, }, {5, 10, 15, },
# sum of subsets of all the subsets of an array | o ( n ) | python3 implementation of the approach ; to store factorial values ; function to return ncr ; function to return the required sum ; initialising factorial ; multiplier ; finding the value of multipler according to the formula ; to store the final answer ; calculate the final answer ; 

maxN = 10
fact = [0] * maxN


def ncr(n, r):
    return (fact[n] // fact[r]) // fact[n - r]


def findSum(arr, n):
    fact[0] = 1
    for i in range(1, n):
        fact[i] = i * fact[i - 1]
    mul = 0
    for i in range(n):
        mul += (2 ** i) * ncr(n - 1, i)
    ans = 0
    for i in range(n):
        ans += mul * arr[i]
    return ans


if __name__ == "__main__":
    arr = [1, 1]
    n = len(arr)
    print(findSum(arr, n))

# Expected output:
6
# count number of ways to reach destination in a maze | python3 implementation of the approach ; function to return the count of possible paths in a maze [ r ] [ c ] from ( 0 , 0 ) to ( r - 1 , c - 1 ) that do not pass through any of the marked cells ; if the initial cell is blocked , there is no way of moving anywhere ; initializing the leftmost column ; if we encounter a blocked cell in leftmost row , there is no way of visiting any cell directly below it . ; similarly initialize the topmost row ; if we encounter a blocked cell in bottommost row , there is no way of visiting any cell directly below it . ; the only difference is that if a cell is - 1 , simply ignore it else recursively compute count value maze [ i ] [ j ] ; if blockage is found , ignore this cell ; if we can reach maze [ i ] [ j ] from maze [ i - 1 ] [ j ] then increment count . ; if we can reach maze [ i ] [ j ] from maze [ i ] [ j - 1 ] then increment count . ; if the final cell is blocked , output 0 , otherwise the answer ; function to return the count of all possible paths from ( 0 , 0 ) to ( n - 1 , m - 1 ) ; we have to calculate m + n - 2 c n - 1 here which will be ( m + n - 2 ) ! / ( n - 1 ) ! ( m - 1 ) ! ; function to return the total count of paths from ( 0 , 0 ) to ( n - 1 , m - 1 ) that pass through at least one of the marked cells ; total count of paths - total paths that do not pass through any of the marked cell ; return answer ; 

R = 4
C = 4


def countPaths(maze):
    if (maze[0][0] == -1):
        return 0
    for i in range(R):
        if (maze[i][0] == 0):
            maze[i][0] = 1
        else:
            break
    for i in range(1, C):
        if (maze[0][i] == 0):
            maze[0][i] = 1
        else:
            break
    for i in range(1, R):
        for j in range(1, C):
            if (maze[i][j] == -1):
                continue
            if (maze[i - 1][j] > 0):
                maze[i][j] = (maze[i][j] + maze[i - 1][j])
            if (maze[i][j - 1] > 0):
                maze[i][j] = (maze[i][j] + maze[i][j - 1])
    if (maze[R - 1][C - 1] > 0):
        return maze[R - 1][C - 1]
    else:
        return 0


def numberOfPaths(m, n):
    path = 1
    for i in range(n, m + n - 1):
        path *= i
        path //= (i - n + 1)
    return path


def solve(maze):
    ans = (numberOfPaths(R, C) - countPaths(maze))
    return ans


maze = [[0, 0, 0, 0], [0, -1, 0, 0], [-1, 0, 0, 0], [0, 0, 0, 0]]
print(solve(maze))

# Expected output:
16
# rat in a maze with multiple steps or jump allowed | maze size ; a utility function to prsolution 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 feasible solutions . ; a recursive utility function to solve maze problem ; if ( x , y is goal ) return true ; check if maze [ x ] [ y ] is valid ; mark x , y as part of solution path ; move forward in x direction ; move forward in x direction ; if moving in x direction doesn 't give  solution then move down 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 range(N):
        for j in range(N):
            print(sol[i][j], end=" ")
        print()


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


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


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


maze = [[2, 1, 0, 0], [3, 0, 0, 1], [0, 1, 0, 1], [0, 0, 0, 1]]
solveMaze(maze)

# Expected output:
1 0 0 0 
1 0 0 1 
0 0 0 1 
0 0 0 1
# prime numbers after prime p with sum s | python program to print all n primes after prime p whose sum equals s ; vector to store prime and n primes whose sum equals given s ; function to check prime number ; square root of x ; since 1 is not prime number ; if any factor is found return false ; no factor found ; function to display n primes whose sum equals s ; function to evaluate all possible n primes whose sum equals s ; if total equals s and total is reached using n primes ; display the n primes ; if total is greater than s or if index has reached last element ; add prime [ index ] to set vector ; include the ( index ) th prime to total ; remove element from set vector ; exclude ( index ) th prime ; function to generate all primes ; all primes less than s itself ; if i is prime add it to prime vector ; if primes are less than n ; 

import math
set = []
prime = []


def isPrime(x):
    sqroot = int(math .sqrt(x))
    flag = True
    if (x == 1):
        return False
    for i in range(2, sqroot + 1):
        if (x % i == 0):
            return False
    return True


def display():
    global set, prime
    length = len(set)
    for i in range(0, length):
        print(set[i], end=" ")
    print()


def primeSum(total, N, S, index):
    global set, prime
    if (total == S and len(set) == N):
        display()
        return
    if (total > S or index == len(prime)):
        return
    set .append(prime[index])
    primeSum(total + prime[index], N, S, index + 1)
    set .pop()
    primeSum(total, N, S, index + 1)


def allPrime(N, S, P):
    global set, prime
    for i in range(P + 1, S + 1):
        if (isPrime(i)):
            prime .append(i)
    if (len(prime) < N):
        return
    primeSum(0, N, S, 0)


S = 54
N = 2
P = 3
allPrime(N, S, P)

# Expected output:
7 47 
11 43 
13 41 
17 37 
23 31
# a backtracking approach to generate n bit gray codes | we have 2 choices for each of the n bits either we can include i . e invert the bit or we can exclude the bit i . e we can leave the number as it is . ; base case when we run out bits to process we simply include it in gray code sequence . ; ignore the bit . ; invert the bit . ; returns the vector containing the gray code sequence of n bits . ; num is passed by reference to keep track of current code . ; 
def grayCodeUtil(res, n, num):
    if (n == 0):
        res .append(num[0])
        return
    grayCodeUtil(res, n - 1, num)
    num[0] = num[0] ^ (1 << (n - 1))
    grayCodeUtil(res, n - 1, num)


def grayCodes(n):
    res = []
    num = [0]
    grayCodeUtil(res, n, num)
    return res


n = 3
code = grayCodes(n)
for i in range(len(code)):
    print(code[i])

# Expected output:
0
1
3
2
6
7
5
4