giulio98/xlcost-single-prompt huggingface dataset:
# minimum operations required to convert all characters of a string to a given character | function to find the minimum number of operations required ; maximum number of characters that can be changed in one operation ; if length of the less than maximum number of characters that can be changed in an operation ; set the last index as the index for the operation ; otherwise ; if size of the is equal to the maximum number of characters in an operation ; find the number of operations required ; find the starting position ; print i - th index ; shift to next index ; otherwise ; find the number of operations required ; if n % div exceeds k ; print i - th index ; shift to next index ; 
def countOperations(n, k):
    div = 2 * k + 1
    if (n // 2 <= k):
        print(1)
        if (n > k):
            print(k + 1)
        else:
            print(n)
    else:
        if (n % div == 0):
            oprn = n // div
            print(oprn)
            pos = k + 1
            print(pos, end=" ")
            for i in range(1, oprn + 1):
                print(pos, end=" ")
                pos += div
        else:
            oprn = n // div + 1
            print(oprn)
            pos = n % div
            if (n % div > k):
                pos -= k
            for i in range(1, oprn + 1):
                print(pos, end=" ")
                pos += div


if __name__ == '__main__':
    str = "edfreqwsazxet"
    ch = '$'
    n = len(str)
    k = 4
    countOperations(n, k)

# Expected output:
2
4 13
# length of largest subsequence consisting of a pair of alternating digits | function to find the length of the largest subsequence consisting of a pair of alternating digits ; variable initialization ; nested loops for iteration ; check if i is not equal to j ; initialize length as 0 ; iterate from 0 till the size of the string ; increment length ; increment length ; update maxi ; check if maxi is not equal to 1 the print otherwise pr0 ; 
def largestSubsequence(s):
    maxi = 0
    for i in range(10):
        for j in range(10):
            if (i != j):
                lenn = 0
                prev1 = chr(j + ord('0'))
                for k in range(len(s)):
                    if (s[k] == chr(i + ord('0'))
                            and prev1 == chr(j + ord('0'))):
                        prev1 = s[k]
                        lenn += 1
                    elif (s[k] == chr(j + ord('0')) and prev1 == chr(i + ord('0'))):
                        prev1 = s[k]
                        lenn += 1
                maxi = max(lenn, maxi)
    if (maxi != 1):
        print(maxi)
    else:
        print(0)


if __name__ == '__main__':
    s = "1542745249842"
    largestSubsequence(s)

# Expected output:
6
# bottom view of a binary tree | tree node class ; constructor of tree node ; printbottomviewutil function ; base case ; if current level is more than or equal to maximum level seen so far for the same horizontal distance or horizontal distance is seen for the first time , update the dictionary ; recur for left subtree by decreasing horizontal distance and increasing level by 1 ; recur for right subtree by increasing horizontal distance and increasing level by 1 ; printbottomview function ; create a dictionary where key -> relative horizontal distance of the node from root node and value -> pair containing node 's  value and its level ; traverse the dictionary in sorted order of their keys and print the bottom view ; 

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


def printBottomViewUtil(root, d, hd, level):
    if root is None:
        return
    if hd in d:
        if level >= d[hd][1]:
            d[hd] = [root .data, level]
    else:
        d[hd] = [root .data, level]
    printBottomViewUtil(root .left, d, hd - 1, level + 1)
    printBottomViewUtil(root .right, d, hd + 1, level + 1)


def printBottomView(root):
    d = dict()
    printBottomViewUtil(root, d, 0, 0)
    for i in sorted(d .keys()):
        print(d[i][0], end=" ")


if __name__ == '__main__':
    root = Node(20)
    root .left = Node(8)
    root .right = Node(22)
    root .left .left = Node(5)
    root .left .right = Node(3)
    root .right .left = Node(4)
    root .right .right = Node(25)
    root .left .right .left = Node(10)
    root .left .right .right = Node(14)
    print("Bottom view of the given binary tree :")
    printBottomView(root)

# Expected output:
Bottom view of the given binary tree :
5 10 4 14 25
# find maximum gcd value from root to leaf in a binary tree | initialise to update the maximum gcd value from all the path ; node structure ; initialize constructor ; function to find gcd of a and b ; function to find the gcd of a path ; function to find the maximum value of gcd from root to leaf in a binary tree ; check if root is not null ; find the maximum gcd of path value and store in global maxm variable ; traverse left of binary tree ; traverse right of the binary tree ; 

global maxm
maxm = 0


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


def gcd(a, b):
    if (b == 0):
        return a
    return gcd(b, a % b)


def find_gcd(arr):
    if (len(arr) == 1):
        return arr[0]
    g = arr[0]
    for i in range(1, len(arr)):
        g = gcd(g, arr[i])
    return g


def maxm_gcd(root, ans):
    global maxm
    if (not root):
        return
    if (root .left is None and root .right is None):
        ans .append(root .val)
        maxm = max(find_gcd(ans), maxm)
        return
    ans .append(root .val)
    maxm_gcd(root .left, ans)
    maxm_gcd(root .right, ans)


if __name__ == '__main__':
    root = Node(15)
    root .left = Node(3)
    root .right = Node(7)
    root .left .left = Node(15)
    root .left .right = Node(1)
    root .right .left = Node(31)
    root .right .right = Node(9)
    maxm_gcd(root, [])
    print(maxm)

# Expected output:
3
# count of pairs with sum n from first n natural numbers | funciton to calculate the value of count ; stores the count of pairs ; set the two pointers ; check if the sum of pirs is equal to n ; increase the count of pairs ; move to the next pair ; 
def numberOfPairs(n):
    count = 0
    i = 1
    j = n - 1
    while (i < j):
        if (i + j) == n:
            count += 1
        i += 1
        j -= 1
    return count


if __name__ == '__main__':
    n = 8
    print(numberOfPairs(n))

# Expected output:
3
# count of ways to generate a matrix with product of each row and column as 1 or | function to return the number of possible ways ; check if product can be - 1 ; 
def Solve(N, M):
    temp = (N - 1) * (M - 1)
    ans = pow(2, temp)
    if ((N + M) % 2 != 0):
        print(ans)
    else:
        print(2 * ans)


if __name__ == '__main__':
    N, M = 3, 3
    Solve(N, M)

# Expected output:
32
# maximum number of bridges in a path of a given graph | python3 program to find the maximum number of bridges in any path of the 

N = 100005
v = []
g = []
vis = [False] * (N)
In = [0] * (N)
low = [0] * (N)
parent = [0] * (N)
rnk = [0] * (N)
bridges = []
n, m = 6, 6
timer = 0
diameter = 0


def swap(x, y):
    temp = x
    x = y
    y = temp


def find_set(a):
    global N, v, g, vis, In, low, parent, rnk, bridges, n, m, timer, diameter
    if parent[a] == a:
        return a
    parent[a] = find_set(parent[a])
    return parent[a]


def union_set(a, b):
    global N, v, g, vis, In, low, parent, rnk, bridges, n, m, timer, diameter
    x, y = find_set(a), find_set(b)
    if x == y:
        return
    if rnk[x] == rnk[y]:
        rnk[x] += 1
    if rnk[y] > rnk[x]:
        swap(x, y)
    parent[y] = x


def dfsBridges(a, par):
    global N, v, g, vis, In, low, parent, rnk, bridges, n, m, timer, diameter
    vis[a] = True
    timer += 1
    In[a], low[a] = timer, timer
    for i in range(len(v[a])):
        if v[a][i] == par:
            continue
        if vis[v[a][i]]:
            low[a] = min(low[a], In[v[a][i]])
        else:
            dfsBridges(v[a][i], a)
        low[a] = min(low[a], low[v[a][i]])
        if In[a] < low[v[a][i]]:
            bridges .append([v[a][i], a])
        else:
            union_set(v[a][i], a)


def dfsDiameter(a, par):
    global N, v, g, vis, In, low, parent, rnk, bridges, n, m, timer, diameter
    x, y = 0, 0
    for i in range(len(g[a])):
        if g[a][i] == par:
            continue
        mx = dfsDiameter(g[a][i], a)
        if mx > x:
            y = x
            x = mx
        elif mx > y:
            y = mx
    diameter = max(diameter, x + y)
    return x + 1


def findMaxBridges():
    global N, v, g, vis, In, low, parent, rnk, bridges, n, m, timer, diameter
    for i in range(n + 1):
        parent[i] = i
        rnk[i] = 1
    dfsBridges(1, 0)
    if len(bridges) == 0:
        return 0
    head = -1
    for i in range(len(bridges)):
        a = find_set(bridges[i][0])
        b = find_set(bridges[i][1])
        g[a].append(b)
        g[b].append(a)
        head = a
    diameter = 0
    dfsDiameter(head, 0)
    return diameter


for i in range(N):
    v .append([])
for i in range(N):
    g .append([])
v[1].append(2)
v[2].append(1)
v[2].append(3)
v[3].append(2)
v[2].append(5)
v[5].append(2)
v[5].append(6)
v[6].append(5)
v[6].append(3)
v[3].append(6)
v[3].append(4)
v[4].append(4)
ans = findMaxBridges()
print(ans)

# Expected output:
2
# Program to count leaf nodes in a binary tree | A Binary tree node ; Function to get the count of leaf nodes in binary tree ; create a tree ; get leaf count of the abve tree

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


def getLeafCount(node):
    if node is None:
        return 0
    if (node .left is None and node .right is None):
        return 1
    else:
        return getLeafCount(node .left) + getLeafCount(node .right)


root = Node(1)
root .left = Node(2)
root .right = Node(3)
root .left .left = Node(4)
root .left .right = Node(5)
print("Leaf count of the tree is %d" % (getLeafCount(root)))

# Expected output:
Leaf count of the tree is 3
# make a palindromic string from given string | function to find winner of the game ; array to maintain frequency of the characters in s initialise freq array with 0 ; maintain count of all distinct characters ; finding frequency of each character ; count unique duplicate characters ; loop to count the unique duplicate characters ; condition for player - 1 to be winner ; else player - 2 is always winner ; 
def palindromeWinner(S):
    freq = [0 for i in range(0, 26)]
    count = 0
    for i in range(0, len(S)):
        if (freq[ord(S[i]) - 97] == 0):
            count += 1
        freq[ord(S[i]) - 97] += 1
    unique = 0
    duplicate = 0
    for i in range(0, 26):
        if (freq[i] == 1):
            unique += 1
        elif (freq[i] >= 2):
            duplicate += 1
    if (unique == 1 and (unique + duplicate) == count):
        return 1
    return 2


S = "abcbc"
print("Player-", palindromeWinner(S))

# Expected output:
Player- 1
# number of substrings with length divisible by the number of 1 's in it | python3 program to count number of substring under given condition ; function return count of such substring ; selection of adequate x value ; store where 1 's are located ; if there are no ones , then answer is 0 ; for ease of implementation ; count storage ; iterate on all k values less than fixed x ; keeps a count of 1 's occured  during string traversal ; iterate on string and modify the totcount ; if this character is 1 ; add to the final sum / count ; increase totcount at exterior position ; reduce totcount at index + k * n ; slightly modified prefix sum storage ; number of 1 's till i-1 ; traversing over string considering each position and finding bounds and count using the inequalities ; calculating bounds for l and r ; if valid then add to answer ; 

import math


def countOfSubstrings(s):
    n = len(s)
    x = int(math .sqrt(n))
    ones = []
    for i in range(n):
        if (s[i] == '1'):
            ones .append(i)
    if (len(ones) == 0):
        return 0
    ones .append(n)
    totCount = [0] * (n * x + n)
    sum = 0
    for k in range(x + 1):
        now = 0
        totCount[k * n] += 1
        for j in range(1, n + 1):
            if (s[j - 1] == '1'):
                now += 1
            index = j - k * now
            sum += totCount[index + k * n]
            totCount[index + k * n] += 1
        now = 0
        totCount[k * n] -= 1
        for j in range(1, n + 1):
            if (s[j - 1] == '1'):
                now += 1
            index = j - k * now
            totCount[index + k * n] -= 1
    prefix_sum = [-1] * n
    cnt = 0
    for i in range(n):
        prefix_sum[i] = cnt
        if (s[i] == '1'):
            cnt += 1
    for k in range(n):
        j = 1
        while (j <= (n // x) and prefix_sum[k] + j <= cnt):
            l = (ones[prefix_sum[k] + j - 1] - k + 1)
            r = ones[prefix_sum[k] + j] - k
            l = max(l, j * (x + 1))
            if (l <= r):
                sum += r // j - (l - 1) // j
            j += 1
    return sum


if __name__ == "__main__":
    S = "1111100000"
    print(countOfSubstrings(S))

# Expected output:
25
# find the largest number smaller than integer n with maximum number of set bits | function to return the largest number less than n ; iterate through all the numbers ; find the number of set bits for the current number ; check if this number has the highest set bits ; return the result ; 
def largestNum(n):
    num = 0
    max_setBits = 0
    for i in range(n + 1):
        setBits = bin(i).count('1')
        if (setBits >= max_setBits):
            num = i
            max_setBits = setBits
    return num


if __name__ == "__main__":
    N = 345
    print(largestNum(N))

# Expected output:
255
# find the kth smallest element in the sorted generated array | function to return the kth element in b [ ] ; initialize the count array ; reduce n repeatedly to half its value ; add count to start ; subtract same count after end index ; store each element of array [ ] with their count ; sort the elements wrt value ; if kth element is in range of element [ i ] return element [ i ] ; if k is out of bound ; 
def solve(Array, N, K):
    count_Arr = [0] * (N + 2)
    factor = 1
    size = N
    while (size):
        start = 1
        end = size
        count_Arr[1] += factor * N
        count_Arr[end + 1] -= factor * N
        factor += 1
        size //= 2
    for i in range(2, N + 1):
        count_Arr[i] += count_Arr[i - 1]
    element = []
    for i in range(N):
        element .append((Array[i], count_Arr[i + 1]))
    element .sort()
    start = 1
    for i in range(N):
        end = start + element[i][1] - 1
        if (K >= start and K <= end):
            return element[i][0]
        start += element[i][1]
    return -1


if __name__ == "__main__":
    arr = [2, 4, 5, 1]
    N = len(arr)
    K = 13
    print(solve(arr, N, K))

# Expected output:
2
# maximum number that can be display on seven segment display using n segments | function to print maximum number that can be formed using n segments ; if n is odd ; use 3 three segment to print 7 ; remaining to print 1 ; if n is even ; print n / 2 1 s . ; 
def printMaxNumber(n):
    if (n % 2 == 1):
        print("7", end="")
        for i in range(int((n - 3) / 2)):
            print("1", end="")
    else:
        for i in range(n / 2):
            print("1", end="")


n = 5
printMaxNumber(n)

# Expected output:
71
# find the sum of digits of a number at even and odd places | function to find the sum of the odd and even positioned digits in a number ; to store the respective sums ; converting integer to string ; traversing the string ; 
def getSum(n):
    sumOdd = 0
    sumEven = 0
    num = str(n)
    for i in range(len(num)):
        if (i % 2 == 0):
            sumOdd = sumOdd + int(num[i])
        else:
            sumEven = sumEven + int(num[i])
    print("Sum odd = ", sumOdd)
    print("Sum even = ", sumEven)


if __name__ == "__main__":
    n = 457892
    getSum(n)

# Expected output:
Sum odd =  20
Sum even =  15
# iterative program to count leaf nodes in a binary tree | node class ; program to count leaves ; if the node itself is " none " return 0 , as there are no leaves ; it the node is a leaf then both right and left children will be " none " ; now we count the leaves in the left and right subtrees and return the sum ; 

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


def countLeaves(node):
    if (node is None):
        return 0
    if (node .left is None and node .right is None):
        return 1
    return countLeaves(node .left) + countLeaves(node .right)


if __name__ == '__main__':
    root = Node(1)
    root .left = Node(2)
    root .right = Node(3)
    root .left .left = Node(4)
    root .left .right = Node(5)
    print(countLeaves(root))

# Expected output:
3
# partition an array such into maximum increasing segments | python 3 program to divide into maximum number of segments ; returns the maximum number of sorted subarrays in a valid partition ; find minimum value from right for every index ; finding the shortest prefix such that all the elements in the prefix are less than or equal to the elements in the rest of the array . ; if current max is less than the right prefix min , we increase number of partitions . ; 

import sys


def sorted_partitions(arr, n):
    right_min = [0] * (n + 1)
    right_min[n] = sys .maxsize
    for i in range(n - 1, -1, -1):
        right_min[i] = min(right_min[i + 1], arr[i])
    partitions = 0
    current_max = arr[0]
    for i in range(n):
        current_max = max(current_max, arr[i])
        if (current_max <= right_min[i + 1]):
            partitions += 1
    return partitions


arr = [3, 1, 2, 4, 100, 7, 9]
n = len(arr)
ans = sorted_partitions(arr, n)
print(ans)

# Expected output:
3
# minimize cost with replacement with other allowed | function returns the minimum cost of the array ; 
def getMinCost(arr, n):
    min_ele = min(arr)
    return min_ele * (n - 1)


arr = [4, 2, 5]
n = len(arr)
print(getMinCost(arr, n))

# Expected output:
4
# minimum swaps required to make a binary string alternating | function to count minimum swaps required to make binary string alternating ; stores total number of ones ; stores total number of zeroes ; checking impossible condition ; odd length string ; number of even positions ; stores number of zeroes and ones at even positions ; even length string ; stores number of ones at odd and even position respectively ; 
def countMinSwaps(s):
    N = len(s)
    one = 0
    zero = 0
    for i in range(N):
        if (s[i] == '1'):
            one += 1
        else:
            zero += 1
    if (one > zero + 1 or zero > one + 1):
        return -1
    if (N % 2):
        num = (N + 1) / 2
        one_even = 0
        zero_even = 0
        for i in range(N):
            if (i % 2 == 0):
                if (s[i] == '1'):
                    one_even += 1
                else:
                    zero_even += 1
        if (one > zero):
            return num - one_even
        else:
            return num - zero_even
    else:
        one_odd = 0
        one_even = 0
        for i in range(N):
            if (s[i] == '1'):
                if (i % 2):
                    one_odd += 1
                else:
                    one_even += 1
        return min(N // 2 - one_odd, N // 2 - one_even)


s = "111000"
print(countMinSwaps(s))

# Expected output:
1
# minimum cost to make array size 1 by removing larger of pairs | function to calculate the minimum cost ; minimum cost is n - 1 multiplied with minimum element . ; 
def cost(a, n):
    return ((n - 1) * min(a))


a = [4, 3, 2]
n = len(a)
print(cost(a, n))

# Expected output:
4
# minimum cost for acquiring all coins with k extra coins allowed with every coin | python3 program to acquire all n coins ; function to calculate min cost ; sort the coins value ; calculate no . of coins needed ; calculate sum of all selected coins ; 

import math


def minCost(coin, n, k):
    coin .sort()
    coins_needed = math .ceil(1.0 * n // (k + 1))
    ans = 0
    for i in range(coins_needed - 1 + 1):
        ans += coin[i]
    return ans


coin = [8, 5, 3, 10, 2, 1, 15, 25]
n = len(coin)
k = 3
print(minCost(coin, n, k))

# Expected output:
3
# program for first fit algorithm in memory management | function to allocate memory to blocks as per first fit algorithm ; stores block id of the block allocated to a process ; pick each process and find suitable blocks according to its size ad assign to it ; allocate block j to p [ i ] process ; reduce available memory in this block . ; 
def firstFit(blockSize, m, processSize, n):
    allocation = [-1] * n
    for i in range(n):
        for j in range(m):
            if blockSize[j] >= processSize[i]:
                allocation[i] = j
                blockSize[j] -= processSize[i]
                break
    print(" Process No. Process Size Block no.")
    for i in range(n):
        print(" ", i + 1, " ", processSize[i], " ", end=" ")
        if allocation[i] != -1:
            print(allocation[i] + 1)
        else:
            print("Not Allocated")


if __name__ == '__main__':
    blockSize = [100, 500, 200, 300, 600]
    processSize = [212, 417, 112, 426]
    m = len(blockSize)
    n = len(processSize)
    firstFit(blockSize, m, processSize, n)

# Expected output:
 Process No. Process Size Block no.
  1   212   2
  2   417   5
  3   112   2
  4   426   Not Allocated
# greedy algorithm to find minimum number of coins | python3 program to find minimum number of denominations ; all denominations of indian currency ; initialize result ; traverse through all denomination ; find denominations ; print result ; 
def findMin(V):
    deno = [1, 2, 5, 10, 20, 50, 100, 500, 1000]
    n = len(deno)
    ans = []
    i = n - 1
    while (i >= 0):
        while (V >= deno[i]):
            V -= deno[i]
            ans .append(deno[i])
        i -= 1
    for i in range(len(ans)):
        print(ans[i], end=" ")


if __name__ == '__main__':
    n = 93
    print("Following is minimal number", "of change for", n, ": ", end="")
    findMin(n)

# Expected output:
Following is minimal number of change for 93 : 50 20 20 2 1
# minimize count of array elements to be removed such that at least k elements are equal to their index values | function to minimize the removals of array elements such that atleast k elements are equal to their indices ; store the array as 1 - based indexing copy of first array ; make a dp - table of ( n * n ) size ; delete the current element ; take the current element ; check for the minimum removals ; 
def MinimumRemovals(a, N, K):
    b = [0 for i in range(N + 1)]
    for i in range(N):
        b[i + 1] = a[i]
    dp = [[0 for i in range(N + 1)]for j in range(N + 1)]
    for i in range(N):
        for j in range(i + 1):
            dp[i + 1][j] = max(dp[i + 1][j], dp[i][j])
            dp[i + 1][j + 1] = max(dp[i + 1][j + 1],
                                   dp[i][j] + (1 if (b[i + 1] == j + 1)else 0))
    j = N
    while (j >= 0):
        if (dp[N][j] >= K):
            return (N - j)
        j -= 1
    return -1


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

# Expected output:
2