giulio98/xlcost-single-prompt huggingface dataset:
# dual pivot quicksort | python3 program to implement dual pivot quicksort ; lp means left pivot and rp means right pivot ; p is the left pivot , and q is the right pivot . ; if elements are less than the left pivot ; if elements are greater than or equal to the right pivot ; bring pivots to their appropriate positions . ; returning the indices of the pivots ; 
def partition(arr, low, high):
    if arr[low] > arr[high]:
        arr[low], arr[high] = arr[high], arr[low]
    j = k = low + 1
    g, p, q = high - 1, arr[low], arr[high]
    while k <= g:
        if arr[k] < p:
            arr[k], arr[j] = arr[j], arr[k]
            j += 1
        elif arr[k] >= q:
            while arr[g] > q and k < g:
                g -= 1
            arr[k], arr[g] = arr[g], arr[k]
            g -= 1
            if arr[k] < p:
                arr[k], arr[j] = arr[j], arr[k]
                j += 1
        k += 1
    j -= 1
    g += 1
    arr[low], arr[j] = arr[j], arr[low]
    arr[high], arr[g] = arr[g], arr[high]
    return j, g


def dualPivotQuickSort(arr, low, high):
    if low < high:
        lp, rp = partition(arr, low, high)
        dualPivotQuickSort(arr, low, lp - 1)
        dualPivotQuickSort(arr, lp + 1, rp - 1)
        dualPivotQuickSort(arr, rp + 1, high)


arr = [24, 8, 42, 75, 29, 77, 38, 57]
dualPivotQuickSort(arr, 0, 7)
print('Sorted array: ', end='')
for i in arr:
    print(i, end=' ')
print()

# Expected output:
Sorted array: 8 24 29 38 42 57 75 77
# a sorting algorithm that slightly improves on selection sort | python3 program to implement min max selection sort . ; shifting the min . ; shifting the max . the equal condition happens if we shifted the max to arr [ min_i ] in the previous swap . ; 
def minMaxSelectionSort(arr, n):
    i = 0
    j = n - 1
    while (i < j):
        min = arr[i]
        max = arr[i]
        min_i = i
        max_i = i
        for k in range(i, j + 1, 1):
            if (arr[k] > max):
                max = arr[k]
                max_i = k
            elif (arr[k] < min):
                min = arr[k]
                min_i = k
        temp = arr[i]
        arr[i] = arr[min_i]
        arr[min_i] = temp
        if (arr[min_i] == max):
            temp = arr[j]
            arr[j] = arr[min_i]
            arr[min_i] = temp
        else:
            temp = arr[j]
            arr[j] = arr[max_i]
            arr[max_i] = temp
        i += 1
        j -= 1
    print("Sorted array:", end=" ")
    for i in range(n):
        print(arr[i], end=" ")


if __name__ == '__main__':
    arr = [23, 78, 45, 8, 32, 56, 1]
    n = len(arr)
    minMaxSelectionSort(arr, n)

# Expected output:
Sorted array: 1 8 23 32 45 56 78
# check if a grid can become row | v [ ] is vector of strings . len is length of strings in every row . ; 
def check(v, l):
    n = len(v)
    for i in v:
        i = ''.join(sorted(i))
    for i in range(l - 1):
        for j in range(n):
            if (v[i][j] > v[i + 1][j]):
                return False
    return True


v = ["ebcda", "ihgfj", "klmno", "pqrst", "yvwxu"]
l = 5
if check(v, l):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# sort first half in ascending and second half in descending order | 1 | function to print half of the array in ascending order and the other half in descending order ; sorting the array ; printing first half in ascending order ; printing second half in descending order ; 
def printOrder(arr, n):
    arr .sort()
    for i in range(n // 2):
        print(arr[i], end=" ")
    for j in range(n - 1, n // 2 - 1, -1):
        print(arr[j], end=" ")


if __name__ == "__main__":
    arr = [5, 4, 6, 2, 1, 3, 8, -1]
    n = len(arr)
    printOrder(arr, n)

# Expected output:
-1 1 2 3 8 6 5 4
# find the sub | python 3 program to find subarray with sum closest to 0 ; function to find the subarray ; pick a starting point ; consider current starting point as a subarray and update minimum sum and subarray indexes ; try all subarrays starting with i ; update minimum sum and subarray indexes ; return starting and ending indexes ; 

import sys


def findSubArray(arr, n):
    min_sum = sys .maxsize
    for i in range(n):
        curr_sum = arr[i]
        if (min_sum > abs(curr_sum)):
            min_sum = abs(curr_sum)
            start = i
            end = i
        for j in range(i + 1, n, 1):
            curr_sum = curr_sum + arr[j]
            if (min_sum > abs(curr_sum)):
                min_sum = abs(curr_sum)
                start = i
                end = j
    p = [start, end]
    return p


if __name__ == '__main__':
    arr = [2, -5, 4, -6, -3]
    n = len(arr)
    point = findSubArray(arr, n)
    print("Subarray starting from ", end="")
    print(point[0], "to", point[1])

# Expected output:
Subarray starting from 0 to 2
# find shortest unique prefix for every word in a given list | set 2 ( using sorting ) | python3 program to prshortest unique prefixes for every word . ; create an array to store the results ; sort the array of strings ; compare the first with its only right neighbor ; store the unique prefix of a [ 1 ] from its left neighbor ; compute common prefix of a [ i ] unique from its right neighbor ; compare the new prefix with previous prefix ; store the prefix of a [ i + 1 ] unique from its left neighbour ; compute the unique prefix for the last in sorted array ; 
def uniquePrefix(a):
    size = len(a)
    res = [0] * (size)
    a = sorted(a)
    j = 0
    while (j < min(len(a[0]) - 1, len(a[1]) - 1)):
        if (a[0][j] == a[1][j]):
            j += 1
        else:
            break
    ind = 0
    res[ind] = a[0][0:j + 1]
    ind += 1
    temp_prefix = a[1][0:j + 1]
    for i in range(1, size - 1):
        j = 0
        while (j < min(len(a[i]) - 1, len(a[i + 1]) - 1)):
            if (a[i][j] == a[i + 1][j]):
                j += 1
            else:
                break
        new_prefix = a[i][0:j + 1]
        if (len(temp_prefix) > len(new_prefix)):
            res[ind] = temp_prefix
            ind += 1
        else:
            res[ind] = new_prefix
            ind += 1
        temp_prefix = a[i + 1][0:j + 1]
    j = 0
    sec_last = a[size - 2]
    last = a[size - 1]
    while (j < min(len(sec_last) - 1, len(last) - 1)):
        if (sec_last[j] == last[j]):
            j += 1
        else:
            break
    res[ind] = last[0:j + 1]
    return res


if __name__ == '__main__':
    input = ["zebra", "dog", "duck", "dove"]
    output = uniquePrefix(input)
    print("The shortest unique prefixes " + "in sorted order are : ")
    for i in output:
        print(i, end=" ")

# Expected output:
The shortest unique prefixes in sorted order are : 
dog dov du z
# find maximum height pyramid from the given array of objects | returns maximum number of pyramidcal levels n boxes of given widths . ; sort objects in increasing order of widths ; total width of previous level and total number of objects in previous level ; number of object in current level . ; width of current level . ; picking the object . so increase current width and number of object . ; if current width and number of object are greater than previous . ; update previous width , number of object on previous level . ; reset width of current level , number of object on current level . ; increment number of level . ; 
def maxLevel(boxes, n):
    boxes .sort()
    ans = 1
    prev_width = boxes[0]
    prev_count = 1
    curr_count = 0
    curr_width = 0
    for i in range(1, n):
        curr_width += boxes[i]
        curr_count += 1
        if (curr_width > prev_width and curr_count > prev_count):
            prev_width = curr_width
            prev_count = curr_count
            curr_count = 0
            curr_width = 0
            ans += 1
    return ans


if __name__ == "__main__":
    boxes = [10, 20, 30, 50, 60, 70]
    n = len(boxes)
    print(maxLevel(boxes, n))

# Expected output:
3
# minimum swaps to reach permuted array with at most 2 positions left swaps allowed | this funt merges two sorted arrays and returns inversion count in the arrays . ; i is index for left subarray ; j is index for right subarray ; k is index for resultant merged subarray ; copy the remaining elements of left subarray ( if there are any ) to temp ; copy the remaining elements of right subarray ( if there are any ) to temp ; copy back the merged elements to original array ; an auxiliary recursive function that sorts the input array and returns the number of inversions in the array . ; divide the array into two parts and call _mergesortandcountinv ( ) for each of the parts ; inversion count will be sum of inversions in left - part , right - part and number of inversions in merging ; merge the two parts ; this function sorts the input array and returns the number of inversions in the array ; method returns minimum number of swaps to reach permuted array 'arr ; loop over all elements to check invalid permutation condition ; if an element is at distance more than 2 from its actual position then it is not possible to reach permuted array just by swapping with 2 positions left elements so returning - 1 ; if permuted array is not invalid , then number of inversion in array will be our final answer ; 
def merge(arr, temp, left, mid, right):

    inv_count = 0

    i = left
    j = mid
    k = left
    while (i <= mid - 1) and (j <= right):

        if arr[i] <= arr[j]:
            temp[k] = arr[i]
            k, i = k + 1, i + 1

        else:
            temp[k] = arr[j]
            k, j = k + 1, j + 1
            inv_count = inv_count + (mid - i)
    while i <= mid - 1:
        temp[k] = arr[i]
        k, i = k + 1, i + 1
    while j <= right:
        temp[k] = arr[j]
        k, j = k + 1, j + 1
    for i in range(left, right + 1):
        arr[i] = temp[i]

    return inv_count


def _mergeSort(arr, temp, left, right):

    inv_count = 0
    if right > left:
        mid = (right + left) // 2
        inv_count = _mergeSort(arr, temp, left, mid)
        inv_count += _mergeSort(arr, temp, mid + 1, right)
        inv_count += merge(arr, temp, left, mid + 1, right)

    return inv_count


def mergeSort(arr, array_size):

    temp = [None] * array_size
    return _mergeSort(arr, temp, 0, array_size - 1)


def minSwapToReachArr(arr, N):
    for i in range(0, N):
        if (arr[i] - 1) - i > 2:
            return -1
    numOfInversion = mergeSort(arr, N)
    return numOfInversion


if __name__ == "__main__":
    arr = [1, 2, 5, 3, 4]
    N = len(arr)
    res = minSwapToReachArr(arr, N)
    if res == -1:
        print("Not Possible")
    else:
        print(res)

# Expected output:
2
# sort all even numbers in ascending order and then sort all odd numbers in descending order | to do two way sort . first sort even numbers in ascending order , then odd numbers in descending order . ; make all odd numbers negative ; check for odd ; sort all numbers ; retaining original array ; 
def twoWaySort(arr, n):
    for i in range(0, n):
        if (arr[i] & 1):
            arr[i] *= -1
    arr .sort()
    for i in range(0, n):
        if (arr[i] & 1):
            arr[i] *= -1


arr = [1, 3, 2, 7, 5, 4]
n = len(arr)
twoWaySort(arr, n)
for i in range(0, n):
    print(arr[i], end=" ")

# Expected output:
7 5 3 1 2 4
# possible to form a triangle from array values | method prints possible triangle when array values are taken as sides ; if number of elements are less than 3 , then no triangle is possible ; first sort the array ; loop for all 3 consecutive triplets ; if triplet satisfies triangle condition , break ; 
def isPossibleTriangle(arr, N):
    if N < 3:
        return False
    arr .sort()
    for i in range(N - 2):
        if arr[i] + arr[i + 1] > arr[i + 2]:
            return True


arr = [5, 4, 3, 1, 2]
N = len(arr)
print("Yes"if isPossibleTriangle(arr, N)else "No")

# Expected output:
Yes
# k | python program to find the k - th smallest element after removing some integers from natural number . ; return the k - th smallest element . ; making an array , and mark all number as unmarked . ; marking the number present in the given array . ; if j is unmarked , reduce k by 1. ; if k is 0 return j . ; 

MAX = 1000000


def ksmallest(arr, n, k):
    b = [0] * MAX
    for i in range(n):
        b[arr[i]] = 1
    for j in range(1, MAX):
        if (b[j] != 1):
            k -= 1
        if (k is not 1):
            return j


k = 1
arr = [1]
n = len(arr)
print(ksmallest(arr, n, k))

# Expected output:
2
# sort an array when two halves are sorted | python program to merge two sorted halves of array into single sorted array ; sort the given array using sort stl ; 
def mergeTwoHalf(A, n):
    A .sort()


if __name__ == '__main__':
    A = [2, 3, 8, -1, 7, 10]
    n = len(A)
    mergeTwoHalf(A, n)
    for i in range(n):
        print(A[i], end=" ")

# Expected output:
-1 2 3 7 8 10
# choose k array elements such that difference of maximum and minimum is minimized | return minimum difference of maximum and minimum of k elements of arr [ 0. . n - 1 ] . ; sorting the array . ; find minimum value among all k size subarray . ; 
def minDiff(arr, n, k):
    result = +2147483647
    arr .sort()
    for i in range(n - k + 1):
        result = int(min(result, arr[i + k - 1] - arr[i]))
    return result


arr = [10, 100, 300, 200, 1000, 20, 30]
n = len(arr)
k = 3
print(minDiff(arr, n, k))

# Expected output:
20
# sort even | python3 program to separately sort even - placed and odd placed numbers and place them together in sorted array . ; create evenarr [ ] and oddarr [ ] ; put elements in oddarr [ ] and evenarr [ ] as per their position ; sort evenarr [ ] in ascending order sort oddarr [ ] in descending order ; 
def bitonicGenerator(arr, n):
    evenArr = []
    oddArr = []
    for i in range(n):
        if ((i % 2) == 0):
            evenArr .append(arr[i])
        else:
            oddArr .append(arr[i])
    evenArr = sorted(evenArr)
    oddArr = sorted(oddArr)
    oddArr = oddArr[::-1]
    i = 0
    for j in range(len(evenArr)):
        arr[i] = evenArr[j]
        i += 1
    for j in range(len(oddArr)):
        arr[i] = oddArr[j]
        i += 1


arr = [1, 5, 8, 9, 6, 7, 3, 4, 2, 0]
n = len(arr)
bitonicGenerator(arr, n)
for i in arr:
    print(i, end=" ")

# Expected output:
1 2 3 6 8 9 7 5 4 0
# number of swaps to sort when only adjacent swapping allowed | this function merges two sorted arrays and returns inversion count in the arrays . ; i is index for left subarray ; j is index for right subarray ; k is index for resultant merged subarray ; this is tricky -- see above explanation / diagram for merge ( ) ; copy the remaining elements of left subarray ( if there are any ) to temp ; copy the remaining elements of right subarray ( if there are any ) to temp ; copy back the merged elements to original array ; an auxiliary recursive function that sorts the input array and returns the number of inversions in the array . ; divide the array into two parts and call _mergesortandcountinv ( ) for each of the parts ; inversion count will be sum of inversions in left - part , right - part and number of inversions in merging ; merge the two parts ; this function sorts the input array and returns the number of inversions in the array ; 
def merge(arr, temp, left, mid, right):
    inv_count = 0

    i = left
    j = mid
    k = left
    while ((i <= mid - 1) and (j <= right)):
        if (arr[i] <= arr[j]):
            temp[k] = arr[i]
            k += 1
            i += 1
        else:
            temp[k] = arr[j]
            k += 1
            j += 1
            inv_count = inv_count + (mid - i)
    while (i <= mid - 1):
        temp[k] = arr[i]
        k += 1
        i += 1
    while (j <= right):
        temp[k] = arr[j]
        k += 1
        j += 1
    for i in range(left, right + 1, 1):
        arr[i] = temp[i]
    return inv_count


def _mergeSort(arr, temp, left, right):
    inv_count = 0
    if (right > left):
        mid = int((right + left) / 2)
        inv_count = _mergeSort(arr, temp, left, mid)
        inv_count += _mergeSort(arr, temp, mid + 1, right)
        inv_count += merge(arr, temp, left, mid + 1, right)
    return inv_count


def countSwaps(arr, n):
    temp = [0 for i in range(n)]
    return _mergeSort(arr, temp, 0, n - 1)


if __name__ == '__main__':
    arr = [1, 20, 6, 4, 5]
    n = len(arr)
    print("Number of swaps is", countSwaps(arr, n))

# Expected output:
Number of swaps is 5
# check whether a given number is even or odd | returns true if n is even , else odd ; 
def isEven(n):
    return (n % 2 == 0)


n = 101
print("Even"if isEven(n)else "Odd")

# Expected output:
Odd
# minimum sum of two numbers formed from digits of an array | function to find and return minimum sum of two numbers formed from digits of the array . ; sort the array ; let two numbers be a and b ; fill a and b with every alternate digit of input array ; return the sum ; 
def solve(arr, n):
    arr .sort()
    a = 0
    b = 0
    for i in range(n):
        if (i % 2 != 0):
            a = a * 10 + arr[i]
        else:
            b = b * 10 + arr[i]
    return a + b


arr = [6, 8, 4, 5, 2, 3]
n = len(arr)
print("Sum is ", solve(arr, n))

# Expected output:
Sum is  604
# maximum product of a triplet ( subsequence of size 3 ) in array | python3 program to find a maximum product of a triplet in array of integers ; function to find a maximum product of a triplet in array of integers of size n ; if size is less than 3 , no triplet exists ; will contain max product ; 

import sys


def maxProduct(arr, n):
    if n < 3:
        return -1
    max_product = -(sys .maxsize - 1)
    for i in range(0, n - 2):
        for j in range(i + 1, n - 1):
            for k in range(j + 1, n):
                max_product = max(max_product, arr[i] * arr[j] * arr[k])
    return max_product


arr = [10, 3, 5, 6, 20]
n = len(arr)
max = maxProduct(arr, n)
if max == -1:
    print("No Tripplet Exits")
else:
    print("Maximum product is", max)

# Expected output:
Maximum product is 1200
# maximum product of a triplet ( subsequence of size 3 ) in array | a python3 program to find a maximum product of a triplet in array of integers ; function to find a maximum product of a triplet in array of integers of size n ; if size is less than 3 , no triplet exists ; construct four auxiliary vectors of size n and initialize them by - 1 ; will contain max product ; to store maximum element on left of array ; to store minimum element on left of array ; leftmax [ i ] will contain max element on left of arr [ i ] excluding arr [ i ] . leftmin [ i ] will contain min element on left of arr [ i ] excluding arr [ i ] . ; reset max_sum to store maximum element on right of array ; reset min_sum to store minimum element on right of array ; rightmax [ i ] will contain max element on right of arr [ i ] excluding arr [ i ] . rightmin [ i ] will contain min element on right of arr [ i ] excluding arr [ i ] . ; for all array indexes i except first and last , compute maximum of arr [ i ] * x * y where x can be leftmax [ i ] or leftmin [ i ] and y can be rightmax [ i ] or rightmin [ i ] . ; 

import sys


def maxProduct(arr, n):
    if (n < 3):
        return -1
    leftMin = [-1 for i in range(n)]
    rightMin = [-1 for i in range(n)]
    leftMax = [-1 for i in range(n)]
    rightMax = [-1 for i in range(n)]
    max_product = -sys .maxsize - 1
    max_sum = arr[0]
    min_sum = arr[0]
    for i in range(1, n):
        leftMax[i] = max_sum
        if (arr[i] > max_sum):
            max_sum = arr[i]
        leftMin[i] = min_sum
        if (arr[i] < min_sum):
            min_sum = arr[i]
    max_sum = arr[n - 1]
    min_sum = arr[n - 1]
    for j in range(n - 2, -1, -1):
        rightMax[j] = max_sum
        if (arr[j] > max_sum):
            max_sum = arr[j]
        rightMin[j] = min_sum
        if (arr[j] < min_sum):
            min_sum = arr[j]
    for i in range(1, n - 1):
        max1 = max(
            arr[i] *
            leftMax[i] *
            rightMax[i],
            arr[i] *
            leftMin[i] *
            rightMin[i])
        max2 = max(
            arr[i] *
            leftMax[i] *
            rightMin[i],
            arr[i] *
            leftMin[i] *
            rightMax[i])
        max_product = max(max_product, max(max1, max2))
    return max_product


arr = [1, 4, 3, -6, -7, 0]
n = len(arr)
Max = maxProduct(arr, n)
if (Max == -1):
    print("No Triplet Exists")
else:
    print("Maximum product is", Max)

# Expected output:
Maximum product is 168
# maximum product of a triplet ( subsequence of size 3 ) in array | function to find a maximum product of a triplet in array of integers of size n ; if size is less than 3 , no triplet exists ; sort the array in ascending order ; return the maximum of product of last three elements and product of first two elements and last element ; 
def maxProduct(arr, n):
    if n < 3:
        return -1
    arr .sort()
    return max(arr[0] * arr[1] * arr[n - 1],
               arr[n - 1] * arr[n - 2] * arr[n - 3])


if __name__ == "__main__":
    arr = [-10, -3, 5, 6, -20]
    n = len(arr)
    _max = maxProduct(arr, n)
    if _max == -1:
        print("No Triplet Exists")
    else:
        print("Maximum product is", _max)

# Expected output:
Maximum product is 1200
# maximum product of a triplet ( subsequence of size 3 ) in array | a o ( n ) python3 program to find maximum product pair in an array . ; function to find a maximum product of a triplet in array of integers of size n ; if size is less than 3 , no triplet exists ; initialize maximum , second maximum and third maximum element ; initialize minimum and second minimum element ; update maximum , second maximum and third maximum element ; update second maximum and third maximum element ; update third maximum element ; update minimum and second minimum element ; update second minimum element ; 

import sys


def maxProduct(arr, n):
    if (n < 3):
        return -1
    maxA = -sys .maxsize - 1
    maxB = -sys .maxsize - 1
    maxC = -sys .maxsize - 1
    minA = sys .maxsize
    minB = sys .maxsize
    for i in range(n):
        if (arr[i] > maxA):
            maxC = maxB
            maxB = maxA
            maxA = arr[i]
        elif (arr[i] > maxB):
            maxC = maxB
            maxB = arr[i]
        elif (arr[i] > maxC):
            maxC = arr[i]
        if (arr[i] < minA):
            minB = minA
            minA = arr[i]
        elif (arr[i] < minB):
            minB = arr[i]
    return max(minA * minB * maxA, maxA * maxB * maxC)


arr = [1, -4, 3, -6, 7, 0]
n = len(arr)
Max = maxProduct(arr, n)
if (Max == -1):
    print("No Triplet Exists")
else:
    print("Maximum product is", Max)

# Expected output:
Maximum product is 168
# minimum operations to convert binary matrix a to b by flipping submatrix of size k | function to count the operations required to convert matrix a to b ; store the sizes of matrix ; stores count of flips required ; traverse the iven matrix ; check if the matrix values are not equal ; increment the count of moves ; check if the current square sized exists or not ; flip all the bits in this square sized submatrix ; count of operations required ; 
def minMoves(a, b, K):
    n = len(a)
    m = len(a[0])
    cntOperations = 0
    for i in range(0, n):
        for j in range(0, m):
            if (a[i][j] != b[i][j]):
                cntOperations += 1
                if (i + K - 1 >= n or j + K - 1 >= m):
                    return -1
                for p in range(0, K):
                    for q in range(0, K):
                        if (a[i + p][j + q] == '0'):
                            a[i + p][j + q] = '1'
                        else:
                            a[i + p][j + q] = '0'
    return cntOperations


if __name__ == "__main__":
    A = [['1', '0', '0'], ['0', '0', '0'], ['0', '0', '0']]
    B = [['0', '0', '0'], ['0', '0', '0'], ['0', '0', '0']]
    K = 3
    print(minMoves(A, B, K))

# Expected output:
-1