giulio98/xlcost-single-prompt huggingface dataset:
# radix sort | a function to do counting sort of arr [ ] according to the digit represented by exp . ; the output array elements that will have sorted arr ; initialize count array as 0 ; store count of occurrences in count [ ] ; change count [ i ] so that count [ i ] now contains actual position of this digit in output array ; build the output array ; copying the output array to arr [ ] , so that arr now contains sorted numbers ; method to do radix sort ; find the maximum number to know number of digits ; do counting sort for every digit . note that instead of passing digit number , exp is passed . exp is 10 ^ i where i is current digit number ; 
def countingSort(arr, exp1):
    n = len(arr)
    output = [0] * (n)
    count = [0] * (10)
    for i in range(0, n):
        index = (arr[i] / exp1)
        count[int(index % 10)] += 1
    for i in range(1, 10):
        count[i] += count[i - 1]
    i = n - 1
    while i >= 0:
        index = (arr[i] / exp1)
        output[count[int(index % 10)] - 1] = arr[i]
        count[int(index % 10)] -= 1
        i -= 1
    i = 0
    for i in range(0, len(arr)):
        arr[i] = output[i]


def radixSort(arr):
    max1 = max(arr)
    exp = 1
    while max1 / exp > 0:
        countingSort(arr, exp)
        exp *= 10


arr = [170, 45, 75, 90, 802, 24, 2, 66]
radixSort(arr)
for i in range(len(arr)):
    print(arr[i])

# Expected output:
2
24
45
66
75
90
170
802
# comb sort | to find next gap from current ; shrink gap by shrink factor ; function to sort arr [ ] using comb sort ; initialize gap ; initialize swapped as true to make sure that loop runs ; keep running while gap is more than 1 and last iteration caused a swap ; find next gap ; initialize swapped as false so that we can check if swap happened or not ; compare all elements with current gap ;  ;  ; 
def getNextGap(gap):
    gap = (gap * 10)//13
    if gap < 1:
        return 1
    return gap


def combSort(arr):
    n = len(arr)
    gap = n
    swapped = True
    while gap != 1 or swapped == 1:
        gap = getNextGap(gap)
        swapped = False
        for i in range(0, n-gap):
            if arr[i] > arr[i + gap]:
                arr[i], arr[i + gap] = arr[i + gap], arr[i]
                swapped = True


arr = [8, 4, 1, 3, -44, 23, -6, 28, 0]
combSort(arr)

print("Sorted array:")
for i in range(len(arr)):
    print(arr[i], end=" ")

# Expected output:
Sorted array:
-44 -6 0 1 3 4 8 23 28
# cycle sort | function sort the array using cycle sort ; count number of memory writes ; loop through the array to find cycles to rotate . ; initialize item as starting point ; find where to put the item . ; if the item is already there , this is not a cycle . ; otherwise , put the item there or right after any duplicates . ; put the item to it 's right position ; rotate the rest of the cycle . ; find where to put the item . ; put the item there or right after any duplicates . ; put the item to it 's right position ; 
def cycleSort(array):
    writes = 0
    for cycleStart in range(0, len(array) - 1):
        item = array[cycleStart]
        pos = cycleStart
        for i in range(cycleStart + 1, len(array)):
            if array[i] < item:
                pos += 1
        if pos == cycleStart:
            continue
        while item == array[pos]:
            pos += 1
        array[pos], item = item, array[pos]
        writes += 1
        while pos != cycleStart:
            pos = cycleStart
            for i in range(cycleStart + 1, len(array)):
                if array[i] < item:
                    pos += 1
            while item == array[pos]:
                pos += 1
            array[pos], item = item, array[pos]
            writes += 1

    return writes


arr = [1, 8, 3, 9, 10, 10, 2, 4]
n = len(arr)
cycleSort(arr)
print("After sort : ")
for i in range(0, n):
    print(arr[i], end=' ')

# Expected output:
After sort : 
1 2 3 4 8 9 10 10
# iterative quick sort | function takes last element as pivot , places the pivot element at its correct position in sorted array , and places all smaller ( smaller than pivot ) to left of pivot and all greater elements to right of pivot ; the main function that implements quicksort arr [ ] -- > array to be sorted , low -- > starting index , high -- > ending index function to do quick sort ; pi is partitioning index , arr [ p ] is now at right place ; 
def partition(arr, low, high):
    i = (low - 1)
    pivot = arr[high]
    for j in range(low, high):
        if arr[j] <= pivot:
            i += 1
            arr[i], arr[j] = arr[j], arr[i]
    arr[i + 1], arr[high] = arr[high], arr[i + 1]
    return (i + 1)


def quickSort(arr, low, high):
    if low < high:
        pi = partition(arr, low, high)
        quickSort(arr, low, pi - 1)
        quickSort(arr, pi + 1, high)


if __name__ == '__main__':
    arr = [4, 2, 6, 9, 2]
    n = len(arr)
    quickSort(arr, 0, n - 1)
    for i in range(n):
        print(arr[i], end=" ")

# Expected output:
2 2 4 6 9
# iterative quick sort | this function is same in both iterative and recursive ; function to do quick sort arr [ ] -- > array to be sorted , l -- > starting index , h -- > ending index ; create an auxiliary stack ; initialize top of stack ; push initial values of l and h to stack ; keep popping from stack while is not empty ; pop h and l ; set pivot element at its correct position in sorted array ; if there are elements on left side of pivot , then push left side to stack ; if there are elements on right side of pivot , then push right side to stack ; 
def partition(arr, l, h):
    i = (l - 1)
    x = arr[h]
    for j in range(l, h):
        if arr[j] <= x:
            i = i + 1
            arr[i], arr[j] = arr[j], arr[i]
    arr[i + 1], arr[h] = arr[h], arr[i + 1]
    return (i + 1)


def quickSortIterative(arr, l, h):
    size = h - l + 1
    stack = [0] * (size)
    top = -1
    top = top + 1
    stack[top] = l
    top = top + 1
    stack[top] = h
    while top >= 0:
        h = stack[top]
        top = top - 1
        l = stack[top]
        top = top - 1
        p = partition(arr, l, h)
        if p - 1 > l:
            top = top + 1
            stack[top] = l
            top = top + 1
            stack[top] = p - 1
        if p + 1 < h:
            top = top + 1
            stack[top] = p + 1
            top = top + 1
            stack[top] = h


arr = [4, 3, 5, 2, 1, 3, 2, 3]
n = len(arr)
quickSortIterative(arr, 0, n - 1)
print("Sorted array is:")
for i in range(n):
    print("% d" % arr[i]),

# Expected output:
Sorted array is:
 1
 2
 2
 3
 3
 3
 4
 5
# sort n numbers in range from 0 to n ^ 2 | a function to do counting sort of arr [ ] according to the digit represented by exp . ; output array ; store count of occurrences in count [ ] ; change count [ i ] so that count [ i ] now contains actual position of this digit in output [ ] ; build the output array ; copy the output array to arr [ ] , so that arr [ ] now contains sorted numbers according to current digit ; the main function to that sorts arr [ ] of size n using radix sort ; do counting sort for first digit in base n . note that instead of passing digit number , exp ( n ^ 0 = 1 ) is passed . ; do counting sort for second digit in base n . note that instead of passing digit number , exp ( n ^ 1 = n ) is passed . ; 
def countSort(arr, n, exp):
    output = [0] * n
    count = [0] * n
    for i in range(n):
        count[i] = 0
    for i in range(n):
        count[(arr[i] // exp) % n] += 1
    for i in range(1, n):
        count[i] += count[i - 1]
    for i in range(n - 1, -1, -1):
        output[count[(arr[i] // exp) % n] - 1] = arr[i]
        count[(arr[i] // exp) % n] -= 1
    for i in range(n):
        arr[i] = output[i]


def sort(arr, n):
    countSort(arr, n, 1)
    countSort(arr, n, n)


if __name__ == "__main__":
    arr = [40, 12, 45, 32, 33, 1, 22]
    n = len(arr)
    print("Given array is")
    print(*arr)
    sort(arr, n)
    print("Sorted array is")
    print(*arr)

# Expected output:
Given array is
40 12 45 32 33 1 22
Sorted array is
1 12 22 32 33 40 45
# search in an almost sorted array | a recursive binary search based function . it returns index of x in given array arr [ l . . r ] is present , otherwise - 1 ; if the element is present at one of the middle 3 positions ; if element is smaller than mid , then it can only be present in left subarray ; else the element can only be present in right subarray ; we reach here when element is not present in array ; 
def binarySearch(arr, l, r, x):
    if (r >= l):
        mid = int(l + (r - l) / 2)
        if (arr[mid] == x):
            return mid
        if (mid > l and arr[mid - 1] == x):
            return (mid - 1)
        if (mid < r and arr[mid + 1] == x):
            return (mid + 1)
        if (arr[mid] > x):
            return binarySearch(arr, l, mid - 2, x)
        return binarySearch(arr, mid + 2, r, x)
    return -1


arr = [3, 2, 10, 4, 40]
n = len(arr)
x = 4
result = binarySearch(arr, 0, n - 1, x)
if (result == -1):
    print("Element is not present in array")
else:
    print("Element is present at index", result)

# Expected output:
Element is present at index 3
# find the closest pair from two sorted arrays | python3 program to find the pair from two sorted arays such that the sum of pair is closest to a given number x ; ar1 [ 0. . m - 1 ] and ar2 [ 0. . n - 1 ] are two given sorted arrays and x is given number . this function prints the pair from both arrays such that the sum of the pair is closest to x . ; initialize the diff between pair sum and x . ; start from left side of ar1 [ ] and right side of ar2 [ ] ; if this pair is closer to x than the previously found closest , then update res_l , res_r and diff ; if sum of this pair is more than x , move to smaller side ; move to the greater side ; print the result ; 

import sys


def printClosest(ar1, ar2, m, n, x):
    diff = sys .maxsize
    l = 0
    r = n - 1
    while (l < m and r >= 0):
        if abs(ar1[l] + ar2[r] - x) < diff:
            res_l = l
            res_r = r
            diff = abs(ar1[l] + ar2[r] - x)
        if ar1[l] + ar2[r] > x:
            r = r - 1
        else:
            l = l + 1
    print("The closest pair is [", ar1[res_l], ",", ar2[res_r], "]")


ar1 = [1, 4, 5, 7]
ar2 = [10, 20, 30, 40]
m = len(ar1)
n = len(ar2)
x = 38
printClosest(ar1, ar2, m, n, x)

# Expected output:
The closest pair is [ 7 , 30 ]
# given a sorted array and a number x , find the pair in array whose sum is closest to x | python3 program to find the pair with sum closest to a given no . a sufficiently large value greater than any element in the input array ; prints the pair with sum closest to x ; to store indexes of result pair ; initialize left and right indexes and difference between pair sum and x ; while there are elements between l and r ; check if this pair is closer than the closest pair so far ; if this pair has more sum , move to smaller values . ; move to larger values ; 

MAX_VAL = 1000000000


def printClosest(arr, n, x):
    res_l, res_r = 0, 0
    l, r, diff = 0, n - 1, MAX_VAL
    while r > l:
        if abs(arr[l] + arr[r] - x) < diff:
            res_l = l
            res_r = r
            diff = abs(arr[l] + arr[r] - x)
        if arr[l] + arr[r] > x:
            r -= 1
        else:
            l += 1
    print('The closest pair is {} and {}'.format(arr[res_l], arr[res_r]))


if __name__ == "__main__":
    arr = [10, 22, 28, 29, 30, 40]
    n = len(arr)
    x = 54
    printClosest(arr, n, x)

# Expected output:
The closest pair is 22 and 30
# count 1 's in a sorted binary array | returns counts of 1 's in arr[low..high]. the array is assumed to be sorted in non-increasing order ; get the middle index ; check if the element at middle index is last 1 ; if element is not last 1 , recur for right side ; else recur for left side ; 
def countOnes(arr, low, high):
    if high >= low:
        mid = low + (high - low) // 2
        if ((mid == high or arr[mid + 1] == 0) and (arr[mid] == 1)):
            return mid + 1
        if arr[mid] == 1:
            return countOnes(arr, (mid + 1), high)
        return countOnes(arr, low, mid - 1)
    return 0


arr = [1, 1, 1, 1, 0, 0, 0]
print("Count of 1's in given array is", countOnes(arr, 0, len(arr) - 1))

# Expected output:
Count of 1's in given array is 4
# minimum adjacent swaps to move maximum and minimum to corners | function that returns the minimum swaps ; index of leftmost largest element ; index of rightmost smallest element ; 
def minSwaps(arr):
    n = len(arr)
    maxx, minn, l, r = -1, arr[0], 0, 0
    for i in range(n):
        if arr[i] > maxx:
            maxx = arr[i]
            l = i
        if arr[i] <= minn:
            minn = arr[i]
            r = i
    if r < l:
        print(l + (n - r - 2))
    else:
        print(l + (n - r - 1))


arr = [5, 6, 1, 3]
minSwaps(arr)

# Expected output:
2
# activity selection problem | greedy algo | prints a maximum set of activities that can be done by a single person , one at a time n -- > total number of activities s [ ] -- > an array that contains start time of all activities f [ ] -- > an array that contains finish time of all activities ; the first activity is always selected ; consider rest of the activities ; if this activity has start time greater than or equal to the finish time of previously selected activity , then select it ; 
def printMaxActivities(s, f):
    n = len(f)
    print("The following activities are selected")
    i = 0
    print(i,)
    for j in range(n):
        if s[j] >= f[i]:
            print(j,)
            i = j


s = [1, 3, 0, 5, 8, 5]
f = [2, 4, 6, 7, 9, 9]
printMaxActivities(s, f)

# Expected output:
The following activities are selected
0
1
3
4
# activity selection problem | greedy algo | returns count of the maximum set of activities that can be done by a single person , one at a time . ; sort jobs according to finish time ; the first activity always gets selected ; consider rest of the activities ; if this activity has start time greater than or equal to the finish time of previously selected activity , then select it ; 
def MaxActivities(arr, n):
    selected = []
    Activity .sort(key=lambda x: x[1])
    i = 0
    selected .append(arr[i])
    for j in range(1, n):
        if arr[j][0] >= arr[i][1]:
            selected .append(arr[j])
            i = j
    return selected


Activity = [[5, 9], [1, 2], [3, 4], [0, 6], [5, 7], [8, 9]]
n = len(Activity)
selected = MaxActivities(Activity, n)
print("Following activities are selected :")
print(selected)

# Expected output:
Following activities are selected :
[[1, 2], [3, 4], [5, 7], [8, 9]]
# longest increasing subsequence | dp | global variable to store the maximum ; to make use of recursive calls , this function must return two things : 1 ) length of lis ending with element arr [ n - 1 ] . we use max_ending_here for this purpose 2 ) overall maximum as the lis may end with an element before arr [ n - 1 ] max_ref is used this purpose . the value of lis of full array of size n is stored in * max_ref which is our final result ; base case ; maxendinghere is the length of lis ending with arr [ n - 1 ] ; recursively get all lis ending with arr [ 0 ] , arr [ 1 ] . . arr [ n - 2 ] if arr [ n - 1 ] is maller than arr [ n - 1 ] , and max ending with arr [ n - 1 ] needs to be updated , then update it ; compare maxendinghere with overall maximum . and update the overall maximum if needed ; return length of lis ending with arr [ n - 1 ] ; the wrapper function for _lis ( ) ; maximum variable holds the result ; the function _lis ( ) stores its result in maximum ; returns max ; 

global maximum


def _lis(arr, n):
    global maximum
    if n == 1:
        return 1
    maxEndingHere = 1
    for i in range(1, n):
        res = _lis(arr, i)
        if arr[i - 1] < arr[n - 1] and res + 1 > maxEndingHere:
            maxEndingHere = res + 1
    maximum = max(maximum, maxEndingHere)
    return maxEndingHere


def lis(arr):
    global maximum
    n = len(arr)
    maximum = 1
    _lis(arr, n)
    return maximum


arr = [10, 22, 9, 33, 21, 50, 41, 60]
n = len(arr)
print("Length of lis is ", lis(arr))

# Expected output:
Length of lis is  5
# longest increasing subsequence | dp | lis returns length of the longest increasing subsequence in arr of size n ; declare the list ( array ) for lis and initialize lis values for all indexes ; compute optimized lis values in bottom up manner ; initialize maximum to 0 to get the maximum of all lis ; pick maximum of all lis values ; 
def lis(arr):
    n = len(arr)
    lis = [1] * n
    for i in range(1, n):
        for j in range(0, i):
            if arr[i] > arr[j] and lis[i] < lis[j] + 1:
                lis[i] = lis[j] + 1
    maximum = 0
    for i in range(n):
        maximum = max(maximum, lis[i])
    return maximum


arr = [10, 22, 9, 33, 21, 50, 41, 60]
print("Length of lis is", lis(arr))

# Expected output:
Length of lis is 5
# longest common subsequence | dp | returns length of lcs for x [ 0. . m - 1 ] , y [ 0. . n - 1 ] ; 
def lcs(X, Y, m, n):
    if m == 0 or n == 0:
        return 0
    elif X[m - 1] == Y[n - 1]:
        return 1 + lcs(X, Y, m - 1, n - 1)
    else:
        return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n))


X = "AGGTAB"
Y = "GXTXAYB"
print("Length of LCS is ", lcs(X, Y, len(X), len(Y)))

# Expected output:
Length of LCS is  4
# longest common subsequence | dp | dynamic programming implementation of lcs problem ; returns length of lcs for x [ 0. . m - 1 ] , y [ 0. . n - 1 ] ; following steps build l [ m + 1 ] [ n + 1 ] in bottom up fashion note : l [ i ] [ j ] contains length of lcs of x [ 0. . i - 1 ] and y [ 0. . j - 1 ] ; l [ m ] [ n ] contains the length of lcs of x [ 0. . n - 1 ] & y [ 0. . m - 1 ] ; end of function lcs 
def lcs(X, Y):
    m = len(X)
    n = len(Y)
    L = [[None] * (n + 1)for i in range(m + 1)]
    for i in range(m + 1):
        for j in range(n + 1):
            if i == 0 or j == 0:
                L[i][j] = 0
            elif X[i - 1] == Y[j - 1]:
                L[i][j] = L[i - 1][j - 1] + 1
            else:
                L[i][j] = max(L[i - 1][j], L[i][j - 1])
    return L[m][n]


X = "AGGTAB"
Y = "GXTXAYB"
print("Length of LCS is ", lcs(X, Y))

# Expected output:
Length of LCS is  4
# edit distance | dp |  ; if any string is empty , return the remaining characters of other string ; to check if the recursive tree for given n & m has already been executed ; if characters are equal , execute recursive function for n - 1 , m - 1 ; if characters are nt equal , we need to find the minimum cost out of all 3 operations . ; temp variables ; 
def minDis(s1, s2, n, m, dp):
    if (n == 0):
        return m
    if (m == 0):
        return n
    if (dp[n][m] != -1):
        return dp[n][m]
    if (s1[n - 1] == s2[m - 1]):
        if (dp[n - 1][m - 1] == -1):
            dp[n][m] = minDis(s1, s2, n - 1, m - 1, dp)
            return dp[n][m]
        else:
            dp[n][m] = dp[n - 1][m - 1]
            return dp[n][m]
    else:
        if (dp[n - 1][m] != -1):
            m1 = dp[n - 1][m]
        else:
            m1 = minDis(s1, s2, n - 1, m, dp)

        if (dp[n][m - 1] != -1):
            m2 = dp[n][m - 1]
        else:
            m2 = minDis(s1, s2, n, m - 1, dp)
        if (dp[n - 1][m - 1] != -1):
            m3 = dp[n - 1][m - 1]
        else:
            m3 = minDis(s1, s2, n - 1, m - 1, dp)

        dp[n][m] = 1 + min(m1, min(m2, m3))
        return dp[n][m]


str1 = "voldemort"
str2 = "dumbledore"

n = len(str1)
m = len(str2)
dp = [[-1 for i in range(m + 1)] for j in range(n + 1)]

print(minDis(str1, str2, n, m, dp))

# Expected output:
7
# min cost path | dp | a naive recursive implementation of mcp ( minimum cost path ) problem ; a utility function that returns minimum of 3 integers ; returns cost of minimum cost path from ( 0 , 0 ) to ( m , n ) in mat [ r ] [ c ] ; 

import sys
R = 3
C = 3


def min(x, y, z):
    if (x < y):
        return x if (x < z)else z
    else:
        return y if (y < z)else z


def minCost(cost, m, n):
    if (n < 0 or m < 0):
        return sys .maxsize
    elif (m == 0 and n == 0):
        return cost[m][n]
    else:
        return cost[m][n] + min(minCost(cost, m - 1, n - 1),
                                minCost(cost, m - 1, n), minCost(cost, m, n - 1))


cost = [[1, 2, 3], [4, 8, 2], [1, 5, 3]]
print(minCost(cost, 2, 2))

# Expected output:
8
# min cost path | dp | dynamic programming python implementation of min cost path problem ; instead of following line , we can use int tc [ m + 1 ] [ n + 1 ] or dynamically allocate memoery to save space . the following line is used to keep te program simple and make it working on all compilers . ; initialize first column of total cost ( tc ) array ; initialize first row of tc array ; construct rest of the tc array ; 

R = 3
C = 3


def minCost(cost, m, n):
    tc = [[0 for x in range(C)]for x in range(R)]
    tc[0][0] = cost[0][0]
    for i in range(1, m + 1):
        tc[i][0] = tc[i - 1][0] + cost[i][0]
    for j in range(1, n + 1):
        tc[0][j] = tc[0][j - 1] + cost[0][j]
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            tc[i][j] = min(tc[i - 1][j - 1], tc[i - 1]
                           [j], tc[i][j - 1]) + cost[i][j]
    return tc[m][n]


cost = [[1, 2, 3], [4, 8, 2], [1, 5, 3]]
print(minCost(cost, 2, 2))

# Expected output:
8
# 0 | returns the maximum value that can be put in a knapsack of capacity w ; build table k [ ] [ ] in bottom up manner ; 
def knapSack(W, wt, val, n):
    K = [[0 for x in range(W + 1)]for x in range(n + 1)]
    for i in range(n + 1):
        for w in range(W + 1):
            if i == 0 or w == 0:
                K[i][w] = 0
            elif wt[i - 1] <= w:
                K[i][w] = max(val[i - 1] + K[i - 1]
                              [w - wt[i - 1]], K[i - 1][w])
            else:
                K[i][w] = K[i - 1][w]
    return K[n][W]


val = [60, 100, 120]
wt = [10, 20, 30]
W = 50
n = len(val)
print(knapSack(W, wt, val, n))

# Expected output:
220
# longest palindromic subsequence | dp | a utility function to get max of two integers ; returns the length of the longest palindromic subsequence in seq ; base case 1 : if there is only 1 character ; base case 2 : if there are only 2 characters and both are same ; if the first and last characters match ; if the first and last characters do not match ; 
def max(x, y):
    if (x > y):
        return x
    return y


def lps(seq, i, j):
    if (i == j):
        return 1
    if (seq[i] == seq[j] and i + 1 == j):
        return 2
    if (seq[i] == seq[j]):
        return lps(seq, i + 1, j - 1) + 2
    return max(lps(seq, i, j - 1), lps(seq, i + 1, j))


if __name__ == '__main__':
    seq = "GEEKSFORGEEKS"
    n = len(seq)
    print("The length of the LPS is", lps(seq, 0, n - 1))

# Expected output:
The length of the LPS is 5
# longest palindromic subsequence | dp | returns the length of the longest palindromic subsequence in seq ; create a table to store results of subproblems ; strings of length 1 are palindrome of length 1 ; build the table . note that the lower diagonal values of table are useless and not filled in the process . the values are filled in a manner similar to matrix chain multiplication dp solution ( see https : www . geeksforgeeks . org / dynamic - programming - set - 8 - matrix - chain - multiplication / cl is length of substring ; 
def lps(str):
    n = len(str)
    L = [[0 for x in range(n)]for x in range(n)]
    for i in range(n):
        L[i][i] = 1
    for cl in range(2, n + 1):
        for i in range(n - cl + 1):
            j = i + cl - 1
            if str[i] == str[j] and cl == 2:
                L[i][j] = 2
            elif str[i] == str[j]:
                L[i][j] = L[i + 1][j - 1] + 2
            else:
                L[i][j] = max(L[i][j - 1], L[i + 1][j])
    return L[0][n - 1]


seq = "GEEKS FOR GEEKS"
n = len(seq)
print("The length of the LPS is " + str(lps(seq)))

# Expected output:
The length of the LPS is 7