giulio98/xlcost-single-prompt huggingface dataset:
# convert given integer x to the form 2 ^ n | python3 implementation of the approach ; function to return the count of operations required ; to store the powers of 2 ; temporary variable to store x ; to store the index of smaller number larger than x ; to store the count of operations ; stores the index of number in the form of 2 ^ n - 1 ; if x is already in the form 2 ^ n - 1 then no operation is required ; if number is less than x increase the index ; calculate all the values ( x xor 2 ^ n - 1 ) for all possible n ; only take value which is closer to the number ; if number is in the form of 2 ^ n - 1 then break ; return the count of operations required to obtain the number ; 

MAX = 24


def countOp(x):
    arr = [0] * MAX
    arr[0] = 1
    for i in range(1, MAX):
        arr[i] = arr[i - 1] * 2
    temp = x
    flag = True
    ans = 0
    operations = 0
    flag2 = False
    for i in range(MAX):
        if (arr[i] - 1 == x):
            flag2 = True
        if (arr[i] > x):
            ans = i
            break
    if (flag2):
        return 0
    while (flag):
        if (arr[ans] < x):
            ans += 1
        operations += 1
        for i in range(MAX):
            take = x ^ (arr[i] - 1)
            if (take <= arr[ans] - 1):
                if (take > temp):
                    temp = take
        if (temp == arr[ans] - 1):
            flag = False
            break
        temp += 1
        operations += 1
        x = temp
        if (x == arr[ans] - 1):
            flag = False
    return operations


if __name__ == "__main__":
    x = 39
    print(countOp(x))

# Expected output:
4
# minimum number of given operations required to reduce the array to 0 element | function to return the minimum operations required ; count the frequency of each element ; maximum element from the array ; find all the multiples of i ; delete the multiples ; increment the operations ; 
def minOperations(arr, n):
    result = 0
    freq = [0] * 1000001
    for i in range(0, n):
        freq[arr[i]] += 1
    maxi = max(arr)
    for i in range(1, maxi + 1):
        if freq[i] != 0:
            for j in range(i * 2, maxi + 1, i):
                freq[j] = 0
            result += 1
    return result


if __name__ == "__main__":
    arr = [2, 4, 2, 4, 4, 4]
    n = len(arr)
    print(minOperations(arr, n))

# Expected output:
1
# form lexicographically smallest string with minimum replacements having equal number of 0 s , 1 s and 2 s | python3 implementation of the approach ; function that returns the modified lexicographically smallest string after performing minimum number of given operations ; stores the initial frequencies of characters 0 s , 1 s and 2 s ; stores number of processed characters upto that point of each type ; required number of characters of each type ; if the current type has already reqd number of characters , no need to perform any operation ; process all 3 cases ; check for 1 first ; else 2 ; here we need to check processed [ 1 ] only for 2 since 0 is less than 1 and we can replace it anytime ; here we can replace 2 with 0 and 1 anytime ; keep count of processed characters of each type ; 

import math


def formStringMinOperations(ss):
    count = [0] * 3
    s = list(ss)
    for i in range(len(s)):
        count[ord(s[i]) - ord('0')] += 1
    processed = [0] * 3
    reqd = math .floor(len(s) / 3)
    for i in range(len(s)):
        if (count[ord(s[i]) - ord('0')] == reqd):
            continue
        if (s[i] == '0' and count[0] > reqd and processed[0] >= reqd):
            if (count[1] < reqd):
                s[i] = '1'
                count[1] += 1
                count[0] -= 1
            elif (count[2] < reqd):
                s[i] = '2'
                count[2] += 1
                count[0] -= 1
        if (s[i] == '1' and count[1] > reqd):
            if (count[0] < reqd):
                s[i] = '0'
                count[0] += 1
                count[1] -= 1
            elif (count[2] < reqd and processed[1] >= reqd):
                s[i] = '2'
                count[2] += 1
                count[1] -= 1
        if (s[i] == '2' and count[2] > reqd):
            if (count[0] < reqd):
                s[i] = '0'
                count[0] += 1
                count[2] -= 1
            elif (count[1] < reqd):
                s[i] = '1'
                count[1] += 1
                count[2] -= 1
        processed[ord(s[i]) - ord('0')] += 1
    return ''.join(s)


s = "011200"
print(formStringMinOperations(s))

# Expected output:
011202
# minimum number of adjacent swaps for arranging similar elements together | function to find minimum swaps ; visited array to check if value is seen already ; if the arr [ i ] is seen first time ; stores the number of swaps required to find the correct position of current element 's partner ; increment count only if the current element has not been visited yet ( if is visited , means it has already been placed at its correct position ) ; if current element 's partner is found ; 
def findMinimumAdjacentSwaps(arr, N):
    visited = [False] * (N + 1)
    minimumSwaps = 0
    for i in range(2 * N):
        if (visited[arr[i]] == False):
            visited[arr[i]] = True
            count = 0
            for j in range(i + 1, 2 * N):
                if (visited[arr[j]] == False):
                    count += 1
                elif (arr[i] == arr[j]):
                    minimumSwaps += count
    return minimumSwaps


if __name__ == "__main__":
    arr = [1, 2, 3, 3, 1, 2]
    N = len(arr)
    N //= 2
    print(findMinimumAdjacentSwaps(arr, N))

# Expected output:
5
# largest palindromic number by permuting digits | python3 program to print the largest palindromic number by permuting digits of a number ; function to check if a number can be permuted to form a palindrome number ; counts the occurrence of number which is odd ; if occurrence is odd ; if number exceeds 1 ; function to print the largest palindromic number by permuting digits of a number ; string length ; map that marks the occurrence of a number ; check the possibility of a palindromic number ; string array that stores the largest permuted palindromic number ; pointer of front ; greedily start from 9 to 0 and place the greater number in front and odd in the middle ; if the occurrence of number is odd ; place one odd occurring number in the middle ; decrease the count ; place the rest of numbers greedily ; if all numbers occur even times , then place greedily ; place greedily at front ; 2 numbers are placed , so decrease the count ; increase placing position ; print the largest string thus formed ; 

from collections import defaultdict


def possibility(m, length, s):
    countodd = 0
    for i in range(0, length):
        if m[int(s[i])] & 1:
            countodd += 1
        if countodd > 1:
            return False
    return True


def largestPalindrome(s):
    l = len(s)
    m = defaultdict(lambda: 0)
    for i in range(0, l):
        m[int(s[i])] += 1
    if possibility(m, l, s) == False:
        print("Palindrome cannot be formed")
        return
    largest = [None] * l
    front = 0
    for i in range(9, -1, -1):
        if m[i] & 1:
            largest[l // 2] = chr(i + 48)
            m[i] -= 1
            while m[i] > 0:
                largest[front] = chr(i + 48)
                largest[l - front - 1] = chr(i + 48)
                m[i] -= 2
                front += 1
        else:
            while m[i] > 0:
                largest[front] = chr(i + 48)
                largest[l - front - 1] = chr(i + 48)
                m[i] -= 2
                front += 1
    for i in range(0, l):
        print(largest[i], end="")


if __name__ == "__main__":
    s = "313551"
    largestPalindrome(s)

# Expected output:
531135
# minimum swaps for bracket balancing | function to calculate swaps required ; keep track of '[ ; to count number of encountered ' [ ' ; to track position of next ' [ ' in pos ; to store result ; increment count and move p to next position ; we have encountered an unbalanced part of string ; increment sum by number of swaps required i . e . position of next ' [ ' - current position ; reset count to 1 ; 
def swapCount(s):

    pos = []
    for i in range(len(s)):
        if (s[i] == '['):
            pos .append(i)
    count = 0
    p = 0
    sum = 0
    s = list(s)
    for i in range(len(s)):
        if (s[i] == '['):
            count += 1
            p += 1
        elif (s[i] == ']'):
            count -= 1
        if (count < 0):
            sum += pos[p] - i
            s[i], s[pos[p]] = (s[pos[p]], s[i])
            p += 1
            count = 1
    return sum


s = "[]][]["
print(swapCount(s))
s = "[[][]]"
print(swapCount(s))

# Expected output:
2
0
# minimum cost to cut a board into squares | method returns minimum cost to break board into m * n squares ; sort the horizontal cost in reverse order ; sort the vertical cost in reverse order ; initialize current width as 1 ; loop until one or both cost array are processed ; increase current horizontal part count by 1 ; increase current vertical part count by 1 ; loop for horizontal array , if remains ; loop for vertical array , if remains ; 
def minimumCostOfBreaking(X, Y, m, n):
    res = 0
    X .sort(reverse=True)
    Y .sort(reverse=True)
    hzntl = 1
    vert = 1
    i = 0
    j = 0
    while (i < m and j < n):
        if (X[i] > Y[j]):
            res += X[i] * vert
            hzntl += 1
            i += 1
        else:
            res += Y[j] * hzntl
            vert += 1
            j += 1
    total = 0
    while (i < m):
        total += X[i]
        i += 1
    res += total * vert
    total = 0
    while (j < n):
        total += Y[j]
        j += 1
    res += total * hzntl
    return res


m = 6
n = 4
X = [2, 1, 3, 1, 4]
Y = [4, 1, 2]
print(minimumCostOfBreaking(X, Y, m - 1, n - 1))

# Expected output:
42
# minimize the count of characters to be added or removed to make string repetition of same substring | function to find the minimum of the three numbers ; function to find the minimum number operations required to convert string str1 to str2 using the operations ; stores the results of subproblems ; fill dp [ ] [ ] in bottom up manner ; if str1 is empty , then insert all characters of string str2 ; minimum operations is j ; if str2 is empty , then remove all characters of string str2 ; minimum operations is i ; if the last characters are same , then ignore last character ; if the last character is different , then find the minimum ; perform one of the insert , remove and the replace ; return the minimum number of steps required ; function to find the minimum number of steps to modify the string such that first half and second half becomes the same ; stores the minimum number of operations required ; traverse the given string s ; find the minimum operations ; update the ans ; print the result ; 
def getMin(x, y, z):
    return min(min(x, y), z)


def editDistance(str1, str2, m, n):
    dp = [[0 for i in range(n + 1)]for j in range(m + 1)]
    for i in range(0, m + 1):
        for j in range(0, n + 1):
            if (i == 0):
                dp[i][j] = j
            elif (j == 0):
                dp[i][j] = i
            elif (str1[i - 1] == str2[j - 1]):
                dp[i][j] = dp[i - 1][j - 1]
            else:
                dp[i][j] = 1 + getMin(dp[i][j - 1], dp[i - 1]
                                      [j], dp[i - 1][j - 1])
    return dp[m][n]


def minimumSteps(S, N):
    ans = 10 ** 10
    for i in range(1, N):
        S1 = S[:i]
        S2 = S[i:]
        count = editDistance(S1, S2, len(S1), len(S2))
        ans = min(ans, count)
    print(ans)


S = "aabb"
N = len(S)
minimumSteps(S, N)

# Expected output:
2
# minimize operations to reduce n to 2 by repeatedly reducing by 3 or dividing by 5 | function to find the minimum number of operations to reduce n to 2 by dividing n by 5 or decrementing by 3 ; initialize the dp array ; initialize the array dp [ ] ; for n = 2 number of operations needed is zero ; iterating over the range [ 1 , n ] ; if it 's not possible to  create current n ; multiply with 5 ; adding the value 3 ; checking if not possible to make the number as 2 ; return the minimum number of operations ; 
def minimumOperations(N):
    dp = [0 for i in range(N + 1)]
    for i in range(N + 1):
        dp[i] = 1000000000
    dp[2] = 0
    for i in range(2, N + 1, 1):
        if (dp[i] == 1000000000):
            continue
        if (i * 5 <= N):
            dp[i * 5] = min(dp[i * 5], dp[i] + 1)
        if (i + 3 <= N):
            dp[i + 3] = min(dp[i + 3], dp[i] + 1)
    if (dp[N] == 1000000000):
        return -1
    return dp[N]


if __name__ == '__main__':
    N = 25
    print(minimumOperations(N))

# Expected output:
2
# maximum profit after buying and selling the stocks with transaction fees | set 2 | function to find the maximum profit with transaction fee ; traversing the stocks for each day ; update buy and sell ; return the maximum profit ; 
def MaxProfit(arr, n, transactionFee):
    buy = -arr[0]
    sell = 0
    for i in range(1, n, 1):
        temp = buy
        buy = max(buy, sell - arr[i])
        sell = max(sell, temp + arr[i] - transactionFee)
    return max(sell, buy)


if __name__ == '__main__':
    arr = [6, 1, 7, 2, 8, 4]
    n = len(arr)
    transactionFee = 2
    print(MaxProfit(arr, n, transactionFee))

# Expected output:
8
# maximum path sum from top left to bottom right of a matrix passing through one of the given cells | stores the maximum path sum from the cell ( 1 , 1 ) to ( n , m ) ; stores the maximum path sum from the cell ( j , j ) to ( n , m ) ; function to find the maximum path sum from the cell ( 1 , 1 ) to ( n , m ) ; traverse the first row ; traverse the first column ; traverse the matrix ; update the value of start [ i ] [ j ] ; function to find the maximum path sum from the cell ( j , j ) to ( n , m ) ; traverse the last row ; traverse the last column ; traverse the matrix ; update the value of ending [ i ] [ j ] ; function to find the maximum path sum from the top - left to the bottom right cell such that path contains one of the cells in the array coordinates [ ] [ ] ; initialize the start and the end matrices ; calculate the start matrix ; calculate the end matrix ; stores the maximum path sum ; traverse the coordinates ; update the value of ans ; print the resultant maximum sum path value ; 

start = [[0 for i in range(3)]for j in range(3)]
ending = [[0 for i in range(3)]for j in range(3)]


def calculateStart(n, m):
    for i in range(1, m, 1):
        start[0][i] += start[0][i - 1]
    for i in range(1, n, 1):
        start[i][0] += start[i - 1][0]
    for i in range(1, n, 1):
        for j in range(1, m, 1):
            start[i][j] += max(start[i - 1][j], start[i][j - 1])


def calculateEnd(n, m):
    i = n - 2
    while (i >= 0):
        ending[i][m - 1] += ending[i + 1][m - 1]
        i -= 1
    i = m - 2
    while (i >= 0):
        ending[n - 1][i] += ending[n - 1][i + 1]
        i -= 1
    i = n - 2
    while (i >= 0):
        j = m - 2
        while (j >= 0):
            ending[i][j] += max(ending[i + 1][j], ending[i][j + 1])
            j -= 1
        i -= 1


def maximumPathSum(mat, n, m, q, coordinates):
    for i in range(n):
        for j in range(m):
            start[i][j] = mat[i][j]
            ending[i][j] = mat[i][j]
    calculateStart(n, m)
    calculateEnd(n, m)
    ans = 0
    for i in range(q):
        X = coordinates[i][0] - 1
        Y = coordinates[i][1] - 1
        ans = max(ans, start[X][Y] + ending[X][Y] - mat[X][Y])
    print(ans)


if __name__ == '__main__':
    mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    N = 3
    M = 3
    Q = 2
    coordinates = [[1, 2], [2, 2]]
    maximumPathSum(mat, N, M, Q, coordinates)

# Expected output:
27
# length of longest subset consisting of a 0 s and b 1 s from an array of strings | set 2 | function to find the length of the longest subset of an array of strings with at most a 0 s and b 1 s ; initialize a 2d array with its entries as 0 ; traverse the given array ; store the count of 0 s and 1 s in the current string ; iterate in the range [ a , zeros ] ; iterate in the range [ b , ones ] ; update the value of dp [ i ] [ j ] ; print the result ; 
def MaxSubsetlength(arr, A, B):
    dp = [[0 for i in range(B + 1)]for i in range(A + 1)]
    for str in arr:
        zeros = str .count('0')
        ones = str .count('1')
        for i in range(A, zeros - 1, -1):
            for j in range(B, ones - 1, -1):
                dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1)
    return dp[A][B]


if __name__ == '__main__':
    arr = ["1", "0", "0001", "10", "111001"]
    A, B = 5, 3
    print(MaxSubsetlength(arr, A, B))

# Expected output:
4
# count ways to select n pairs of candies of distinct colors ( dynamic programming + bitmasking ) | function to count ways to select n distinct pairs of candies with different colours ; if n pairs are selected ; stores count of ways to select the i - th pair ; iterate over the range [ 0 , n ] ; if pair ( i , j ) is not included ; 
def numOfWays(a, n, i=0, blue=[]):
    if i == n:
        return 1
    count = 0
    for j in range(n):
        if mat[i][j] == 1 and j not in blue:
            count += numOfWays(mat, n, i + 1, blue + [j])
    return count


if __name__ == "__main__":
    n = 3
    mat = [[0, 1, 1], [1, 0, 1], [1, 1, 1]]
    print(numOfWays(mat, n))

# Expected output:
3
# minimize cost to reach end of an array by two forward jumps or one backward jump in each move | function to find the minimum cost to reach the end of an array ; base case : when n < 3 ; store the results in table ; initialize base cases ; iterate over the range [ 2 , n - 2 ] to construct the dp array ; handle case for the last index , i . e . n - 1 ; print the answer ; 
def minCost(arr, n):
    if (n < 3):
        print(arr[0])
        return
    dp = [0] * n
    dp[0] = arr[0]
    dp[1] = dp[0] + arr[1] + arr[2]
    for i in range(2, n - 1):
        dp[i] = min(dp[i - 2] + arr[i], dp[i - 1] + arr[i] + arr[i + 1])
    dp[n - 1] = min(dp[n - 2], dp[n - 3] + arr[n - 1])
    print(dp[n - 1])


if __name__ == "__main__":
    arr = [9, 4, 6, 8, 5]
    N = len(arr)
    minCost(arr, N)

# Expected output:
20
# calculate the value of 2 raised to the power of twice the binary representation of n | python3 program to implement the above approach ; function to find the value of power ( x , y ) in o ( log y ) ; stores power ( x , y ) ; update x ; base case ; calculate power ( x , y ) ; if y is an odd number ; update res ; update y ; update x ; function to calculate ( 2 ^ ( 2 * x ) ) % ( 10 ^ 9 + 7 ) ; stores binary representation of n ; stores power of 10 ; calculate the binary representation of n ; if n is an odd number ; update x ; update pow_10 ; update n ; double the value of x ; stores the value of ( 2 ^ ( 2 * x ) ) % ( 10 ^ 9 + 7 ) ; 

M = 1000000007


def power(X, Y):
    res = 1
    X = X % M
    if (X == 0):
        return 0
    while (Y > 0):
        if (Y & 1):
            res = (res * X) % M
        Y = Y >> 1
        X = (X * X) % M
    return res


def findValue(n):
    X = 0
    pow_10 = 1
    while (n):
        if (n & 1):
            X += pow_10
        pow_10 *= 10
        n //= 2
    X = (X * 2) % M
    res = power(2, X)
    return res


if __name__ == "__main__":
    n = 2
    print(findValue(n))

# Expected output:
1048576
# calculate the value of 2 raised to the power of twice the binary representation of n | python3 program to implement the above approach ; function to find the value of power ( x , y ) in o ( log y ) ; stores power ( x , y ) ; update x ; base case ; calculate power ( x , y ) ; if y is an odd number ; update res ; update y ; update x ; function to calculate ( 2 ^ ( 2 * x ) ) % ( 10 ^ 9 + 7 ) ; dp [ n ] * dp [ n ] : stores value of ( 2 ^ ( 2 * x ) ) % ( 10 ^ 9 + 7 ) ; base case ; iterate over the range [ 3 , n ] ; stores rightmost bit of i ; stores the value of ( i - y ) ; if x is power of 2 ; update dp [ i ] ; update dp [ i ] ; 

M = 1000000007


def power(X, Y):
    res = 1
    X = X % M
    if (X == 0):
        return 0
    while (Y > 0):
        if (Y % 2 == 1):
            res = (res * X) % M
        Y = Y >> 1
        X = (X * X) % M
    return res


def findValue(N):
    dp = [0] * (N + 1)
    dp[1] = 2
    dp[2] = 1024
    for i in range(3, N + 1):
        y = (i & (-i))
        x = i - y
        if (x == 0):
            dp[i] = power(dp[i // 2], 10)
        else:
            dp[i] = (dp[x] * dp[y]) % M
    return (dp[N] * dp[N]) % M


if __name__ == '__main__':
    n = 150
    print(findValue(n))

# Expected output:
654430484
# count ways to obtain given sum by repeated throws of a dice | function to find the number of ways to get the sum n with throw of dice ; base case ; stores the count of total number of ways to get sum n ; recur for all 6 states ; return answer ; 
def findWays(N):
    if (N == 0):
        return 1
    cnt = 0
    for i in range(1, 7):
        if (N - i >= 0):
            cnt = cnt + findWays(N - i)
    return cnt


if __name__ == '__main__':
    N = 4
    print(findWays(N))

# Expected output:
8
# check if an array can be split into 3 subsequences of equal sum or not | utility function to check array can be partition to 3 subsequences of equal sum or not ; base case ; when element at index j is added to sm1 ; when element at index j is added to sm2 ; when element at index j is added to sm3 ; return maximum value among all above 3 recursive call ; function to check array can be partition to 3 subsequences of equal sum or not ; initialise 3 sums to 0 ; function call ; 
def checkEqualSumUtil(arr, N, sm1, sm2, sm3, j):
    if j == N:
        if sm1 == sm2 and sm2 == sm3:
            return 1
        else:
            return 0
    else:
        l = checkEqualSumUtil(arr, N, sm1 + arr[j], sm2, sm3, j + 1)
        m = checkEqualSumUtil(arr, N, sm1, sm2 + arr[j], sm3, j + 1)
        r = checkEqualSumUtil(arr, N, sm1, sm2, sm3 + arr[j], j + 1)
        return max(l, m, r)


def checkEqualSum(arr, N):
    sum1 = sum2 = sum3 = 0
    if checkEqualSumUtil(arr, N, sum1, sum2, sum3, 0) == 1:
        print("Yes")
    else:
        print("No")


arr = [17, 34, 59, 23, 17, 67, 57, 2, 18, 59, 1]
N = len(arr)
checkEqualSum(arr, N)

# Expected output:
Yes
# check if an array can be split into 3 subsequences of equal sum or not | python3 program for the above approach ; function to check array can be partition into sum of 3 equal ; base case ; if value at particular index is not - 1 then return value at that index which ensure no more further calls ; when element at index j is added to sm1 ; when element at index j is added to sm2 ; when element at index j is added to sm3 ; update the current state and return that value ; function to check array can be partition to 3 subsequences of equal sum or not ; initialise 3 sums to 0 ; function call ; 

dp = {}


def checkEqualSumUtil(arr, N, sm1, sm2, sm3, j):
    s = str(sm1) + "_" + str(sm2) + str(j)
    if j == N:
        if sm1 == sm2 and sm2 == sm3:
            return 1
        else:
            return 0
    if s in dp:
        return dp[s]
    l = checkEqualSumUtil(arr, N, sm1 + arr[j], sm2, sm3, j + 1)
    m = checkEqualSumUtil(arr, N, sm1, sm2 + arr[j], sm3, j + 1)
    r = checkEqualSumUtil(arr, N, sm1, sm2, sm3 + arr[j], j + 1)
    dp[s] = max(l, m, r)
    return dp[s]


def checkEqualSum(arr, N):
    sum1 = sum2 = sum3 = 0
    if checkEqualSumUtil(arr, N, sum1, sum2, sum3, 0) == 1:
        print("Yes")
    else:
        print("No")


arr = [17, 34, 59, 23, 17, 67, 57, 2, 18, 59, 1]
N = len(arr)
checkEqualSum(arr, N)

# Expected output:
Yes