giulio98/xlcost-single-prompt huggingface dataset:
# convert given matrix into sorted spiral matrix | python3 program to convert given matrix into sorted spiral matrix ; function to convert the array to spiral ; for array pointer ; k - starting row index m - ending row index l - starting column index n - ending column index ; print the first row from the remaining rows ; print the last column from the remaining columns ; print the last row from the remaining rows ; print the first column from the remaining columns ; function to convert 2d array to 1d array ; store value 2d matrix to 1d array ; function to print the matrix ; print spiral matrix ; function to sort the array ; sort array using inbuilt function ; function to convert given matrix into sorted spiral matrix ; 

MAX = 1000


def ToSpiral(m, n, Sorted, a):
    index = 0
    k = 0
    l = 0
    while (k < m and l < n):
        for i in range(l, n, 1):
            a[k][i] = Sorted[index]
            index += 1
        k += 1
        for i in range(k, m, 1):
            a[i][n - 1] = Sorted[index]
            index += 1
        n -= 1
        if (k < m):
            i = n - 1
            while (i >= l):
                a[m - 1][i] = Sorted[index]
                index += 1
                i -= 1
            m -= 1
        if (l < n):
            i = m - 1
            while (i >= k):
                a[i][l] = Sorted[index]
                index += 1
                i -= 1
            l += 1


def convert2Dto1D(y, m, n):
    index = 0
    x = [0 for i in range(m * n)]
    for i in range(m):
        for j in range(n):
            x[index] = y[i][j]
            index += 1
    return x


def PrintMatrix(a, m, n):
    for i in range(m):
        for j in range(n):
            print(a[i][j], end=" ")
        print('', end="")


def SortArray(x):
    x .sort(reverse=False)
    return x


def convertMatrixToSortedSpiral(y, m, n):
    a = [[0 for i in range(MAX)]for j in range(MAX)]
    x = [0 for i in range(15)]
    x = convert2Dto1D(y, m, n)
    x = SortArray(x)
    ToSpiral(m, n, x, a)
    PrintMatrix(a, m, n)


if __name__ == '__main__':
    m = 4
    n = 3
    y = [[2, 5, 12], [22, 45, 55], [1, 6, 8], [13, 56, 10]]
    convertMatrixToSortedSpiral(y, m, n)

# Expected output:
1 2 5 45 55 6 22 56 8 13 12 10
# find a rotation with maximum hamming distance | return the maximum hamming distance of a rotation ; arr [ ] to brr [ ] two times so that we can traverse through all rotations . ; we know hamming distance with 0 rotation would be 0. ; we try other rotations one by one and compute hamming distance of every rotation ; we can never get more than n . ; 
def maxHamming(arr, n):
    brr = [0] * (2 * n + 1)
    for i in range(n):
        brr[i] = arr[i]
    for i in range(n):
        brr[n + i] = arr[i]
    maxHam = 0
    for i in range(1, n):
        currHam = 0
        k = 0
        for j in range(i, i + n):
            if brr[j] != arr[k]:
                currHam += 1
                k = k + 1
        if currHam == n:
            return n
        maxHam = max(maxHam, currHam)
    return maxHam


arr = [2, 4, 6, 8]
n = len(arr)
print(maxHamming(arr, n))

# Expected output:
4
# Minimum Circles needed to be removed so that all remaining circles are non intersecting | Function to return the count of non intersecting circles ; Structure with start and end of diameter of circles ; Sorting with smallest finish time first ; count stores number of circles to be removed ; cur stores ending of first circle ; Non intersecting circles ; Intersecting circles ; Centers of circles ; Radius of circles ; Number of circles
def CountCircles(c, r, n):
    diameter = []
    for i in range(n):
        obj = []
        obj .append(c[i] - r[i])
        obj .append(c[i] + r[i])
        diameter .append(obj)
    diameter .sort()
    count = 0
    cur = diameter[0][1]
    for i in range(1, n):
        if (diameter[i][0] > cur):
            cur = diameter[i][1]
        else:
            count += 1
    print(count)


c = [1, 2, 3, 4]
r = [1, 1, 1, 1]
n = len(c)
CountCircles(c, r, n)

# Expected output:
2
# print left rotation of array in o ( n ) time and o ( 1 ) space | python3 implementation to print left rotation of any array k times ; function for the k times left rotation ; the collections module has deque class which provides the rotate ( ) , which is inbuilt function to allow rotation ; print the rotated array from start position ; 

from collections import deque


def leftRotate(arr, k, n):
    arr = deque(arr)
    arr .rotate(-k)
    arr = list(arr)
    for i in range(n):
        print(arr[i], end=" ")


if __name__ == '__main__':
    arr = [1, 3, 5, 7, 9]
    n = len(arr)
    k = 2
    leftRotate(arr, k, n)

# Expected output:
5 7 9 1 3
# find element at given index after a number of rotations | function to compute the element at given index ; range [ left ... right ] ; rotation will not have any effect ; returning new element ; 
def findElement(arr, ranges, rotations, index):
    for i in range(rotations - 1, -1, -1):
        left = ranges[i][0]
        right = ranges[i][1]
        if (left <= index and right >= index):
            if (index == left):
                index = right
            else:
                index = index - 1
    return arr[index]


arr = [1, 2, 3, 4, 5]
rotations = 2
ranges = [[0, 2], [0, 3]]
index = 1
print(findElement(arr, ranges, rotations, index))

# Expected output:
3
# sort an alphanumeric string such that the positions of alphabets and numbers remain unchanged | function that returns the string s in sorted form such that the positions of alphabets and numeric digits remain unchanged ; string to character array ; sort the array ; count of alphabets and numbers ; get the index from where the alphabets start ; now replace the string with sorted string ; if the position was occupied by an alphabet then replace it with alphabet ; else replace it with a number ; return the sorted string ; 
def sort(s):
    c, s = list(s), list(s)
    c .sort()
    al_c = 0
    nu_c = 0
    while ord(c[al_c]) < 97:
        al_c += 1
    for i in range(len(s)):
        if s[i] < 'a':
            s[i] = c[nu_c]
            nu_c += 1
        else:
            s[i] = c[al_c]
            al_c += 1
    return ''.join(s)


if __name__ == "__main__":
    s = "d4c3b2a1"
    print(sort(s))

# Expected output:
a1b2c3d4
# Split the array and add the first part to the end | Python program to split array and move first part to end . ; Rotate array by 1. ; main
def splitArr(arr, n, k):
    for i in range(0, k):
        x = arr[0]
        for j in range(0, n - 1):
            arr[j] = arr[j + 1]
        arr[n - 1] = x


arr = [12, 10, 5, 6, 52, 36]
n = len(arr)
position = 2
splitArr(arr, n, position)
for i in range(0, n):
    print(arr[i], end=' ')

# Expected output:
5 6 52 36 12 10
# split the array and add the first part to the end | function to spilt array and move first part to end ; make a temporary array with double the size and each index is initialized to 0 ; copy array element in to new array twice ; 
def SplitAndAdd(A, length, rotation):
    tmp = [0 for i in range(length * 2)]
    for i in range(length):
        tmp[i] = A[i]
        tmp[i + length] = A[i]
    for i in range(rotation, rotation + length, 1):
        A[i - rotation] = tmp[i]


arr = [12, 10, 5, 6, 52, 36]
n = len(arr)
position = 2
SplitAndAdd(arr, n, position)
for i in range(n):
    print(arr[i], end=" ")
print()

# Expected output:
5 6 52 36 12 10
# rearrange an array such that arr [ i ] = i | function to tranform the array ; iterate over the array ; check is any ar [ j ] exists such that ar [ j ] is equal to i ; iterate over array ; if not present ; print the output ; 
def fixArray(ar, n):
    for i in range(n):
        for j in range(n):
            if (ar[j] == i):
                ar[j], ar[i] = ar[i], ar[j]
    for i in range(n):
        if (ar[i] != i):
            ar[i] = -1
    print("Array after Rearranging")
    for i in range(n):
        print(ar[i], end=" ")


ar = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1]
n = len(ar)
fixArray(ar, n)

# Expected output:
Array after Rearranging
-1 1 2 3 4 -1 6 -1 -1 9
# perform k of q queries to maximize the sum of the array elements | function to perform k queries out of q to maximize the final sum ; get the initial sum of the array ; stores the contriution of every query ; sort the contribution of queries in descending order ; get the k most contributions ; 
def getFinalSum(a, n, queries, q, k):
    answer = 0
    for i in range(n):
        answer += a[i]
    contribution = []
    for i in range(q):
        contribution .append(queries[i][1] - queries[i][0] + 1)
    contribution .sort(reverse=True)
    i = 0
    while (i < k):
        answer += contribution[i]
        i += 1
    return answer


if __name__ == '__main__':
    a = [1, 1, 2, 2, 2, 3]
    n = len(a)
    queries = [[0, 4], [1, 2], [2, 5], [2, 3], [2, 4]]
    q = len(queries)
    k = 3
    print(getFinalSum(a, n, queries, q, k))

# Expected output:
23
# queries to return the absolute difference between l | function to return the result for a particular query ; get the difference between the indices of l - th and the r - th smallest element ; return the answer ; function that performs all the queries ; store the array numbers and their indices ; sort the array elements ; answer all the queries ; 
def answerQuery(arr, l, r):
    answer = abs(arr[l - 1][1] - arr[r - 1][1])
    return answer


def solveQueries(a, n, q, m):
    arr = [[0 for i in range(n)]for j in range(n)]
    for i in range(n):
        arr[i][0] = a[i]
        arr[i][1] = i
    arr .sort(reverse=False)
    for i in range(m):
        print(answerQuery(arr, q[i][0], q[i][1]))


if __name__ == '__main__':
    a = [1, 5, 4, 2, 8, 6, 7]
    n = len(a)
    q = [[2, 5], [1, 3], [1, 5], [3, 6]]
    m = len(q)
    solveQueries(a, n, q, m)

# Expected output:
2
2
5
4
# k | python3 implementation of the above approach ; set to store the unique substring ; string to create each substring ; adding to set ; converting set into a list ; sorting the strings int the list into lexicographical order ; printing kth substring ; 
def kThLexString(st, k, n):
    z = set()
    for i in range(n):
        pp = ""
        for j in range(i, i + k):
            if (j >= n):
                break
            pp += s[j]
            z .add(pp)
    fin = sorted(z)
    print(fin[k - 1])


s = "geeksforgeeks"
k = 5
n = len(s)
kThLexString(s, k, n)

# Expected output:
eeksf
# rearrange array such that arr [ i ] >= arr [ j ] if i is even and arr [ i ] <= arr [ j ] if i is odd and j < i | python3 code to rearrange the array as per the given condition ; function to rearrange the array ; total even positions ; total odd positions ; copy original array in an auxiliary array ; sort the auxiliary array ; fill up odd position in original array ; fill up even positions in original array ; display array ; 

import array as a
import numpy as np


def rearrangeArr(arr, n):
    evenPos = int(n / 2)
    oddPos = n - evenPos
    tempArr = np .empty(n, dtype=object)
    for i in range(0, n):
        tempArr[i] = arr[i]
    tempArr .sort()
    j = oddPos - 1
    for i in range(0, n, 2):
        arr[i] = tempArr[j]
        j = j - 1
    j = oddPos
    for i in range(1, n, 2):
        arr[i] = tempArr[j]
        j = j + 1
    for i in range(0, n):
        print(arr[i], end=' ')


arr = a .array('i', [1, 2, 3, 4, 5, 6, 7])
rearrangeArr(arr, 7)

# Expected output:
4 5 3 6 2 7 1
# sort only non | python3 program to sort only non primes ; create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . a value in prime [ i ] will finally be false if i is not a prime , else true . ; if prime [ p ] is not changed , then it is a prime ; update all multiples of p ; function to print the array such that only non primes are sorted ; list v will store all non prime numbers ; if not prime , insert into list ; sorting list of non primes ; print the required array ; 

from math import sqrt
prime = [0] * 100005


def SieveOfEratosthenes(n):
    for i in range(len(prime)):
        prime[i] = True
    prime[1] = False
    for p in range(2, int(sqrt(n)) + 1):
        if prime[p]:
            for i in range(p * 2, n, p):
                prime[i] = False


def sortedArray(arr, n):
    SieveOfEratosthenes(100005)
    v = []
    for i in range(n):
        if prime[arr[i]] == 0:
            v .append(arr[i])
    v .sort()
    j = 0
    for i in range(n):
        if prime[arr[i]]:
            print(arr[i], end=" ")
        else:
            print(v[j], end=" ")
            j += 1


if __name__ == "__main__":
    n = 6
    arr = [100, 11, 500, 2, 17, 1]
    sortedArray(arr, n)

# Expected output:
1 11 100 2 17 500
# minimum swaps required to bring all elements less than or equal to k together | utility function to find minimum swaps required to club all elements less than or equals to k together ; find count of elements which are less than equals to k ; find unwanted elements in current window of size 'count   ; initialize answer with ' bad ' value of current window ; decrement count of previous window ; increment count of current window ; update ans if count of ' bad ' is less in current window ; 
def minSwap(arr, n, k):
    count = 0
    for i in range(0, n):
        if (arr[i] <= k):
            count = count + 1
    bad = 0
    for i in range(0, count):
        if (arr[i] > k):
            bad = bad + 1
    ans = bad
    j = count
    for i in range(0, n):
        if (j == n):
            break
        if (arr[i] > k):
            bad = bad - 1
        if (arr[j] > k):
            bad = bad + 1
        ans = min(ans, bad)
        j = j + 1
    return ans


arr = [2, 1, 5, 6, 3]
n = len(arr)
k = 3
print(minSwap(arr, n, k))
arr1 = [2, 7, 9, 5, 8, 7, 4]
n = len(arr1)
k = 5
print(minSwap(arr1, n, k))

# Expected output:
1
2
# maximum product of subsequence of size k | required function ; sorting given input array ; variable to store final product of all element of sub - sequence of size k ; case i if max element is 0 and k is odd then max product will be 0 ; case ii if all elements are negative and k is odd then max product will be product of rightmost - subarray of size k ; else i is current left pointer index ; j is current right pointer index ; case iii if k is odd and rightmost element in sorted array is positive then it must come in subsequence multiplying a [ j ] with product and correspondingly changing j ; case iv now k is even . so , now we deal with pairs each time a pair is multiplied to product ie . . two elements are added to subsequence each time . effectively k becomes half hence , k >>= 1 means k /= 2 ; now finding k corresponding pairs to get maximum possible value of product ; product from left pointers ; product from right pointers ; taking the max product from two choices . correspondingly changing the pointer 's position ; finally return product ; 
def maxProductSubarrayOfSizeK(A, n, k):
    A .sort()
    product = 1
    if (A[n - 1] == 0 and (k & 1)):
        return 0
    if (A[n - 1] <= 0 and (k & 1)):
        for i in range(n - 1, n - k + 1, -1):
            product *= A[i]
        return product
    i = 0
    j = n - 1
    if (k & 1):
        product *= A[j]
        j -= 1
        k -= 1
    k >>= 1
    for itr in range(k):
        left_product = A[i] * A[i + 1]
        right_product = A[j] * A[j - 1]
        if (left_product > right_product):
            product *= left_product
            i += 2
        else:
            product *= right_product
            j -= 2
    return product


if __name__ == "__main__":
    A = [1, 2, -1, -3, -6, 4]
    n = len(A)
    k = 4
    print(maxProductSubarrayOfSizeK(A, n, k))

# Expected output:
144
# reorder an array according to given indexes | function to reorder elements of arr [ ] according to index [ ] ; arr [ i ] should be present at index [ i ] index ; copy temp [ ] to arr [ ] ; 
def reorder(arr, index, n):
    temp = [0] * n
    for i in range(0, n):
        temp[index[i]] = arr[i]
    for i in range(0, n):
        arr[i] = temp[i]
        index[i] = i


arr = [50, 40, 70, 60, 90]
index = [3, 0, 4, 1, 2]
n = len(arr)
reorder(arr, index, n)
print("Reordered array is:")
for i in range(0, n):
    print(arr[i], end=" ")
print("ModifiedIndexarrayis:")
for i in range(0, n):
    print(index[i], end=" ")

# Expected output:
Reordered array is:
40 60 90 50 70 ModifiedIndexarrayis:
0 1 2 3 4
# reorder an array according to given indexes | function to reorder elements of arr [ ] according to index [ ] ; fix all elements one by one ; while index [ i ] and arr [ i ] are not fixed ; store values of the target ( or correct ) position before placing arr [ i ] there ; place arr [ i ] at its target ( or correct ) position . also copy corrected index for new position ; copy old target values to arr [ i ] and index [ i ] ; 
def reorder(arr, index, n):
    for i in range(0, n):
        while (index[i] != i):
            oldTargetI = index[index[i]]
            oldTargetE = arr[index[i]]
            arr[index[i]] = arr[i]
            index[index[i]] = index[i]
            index[i] = oldTargetI
            arr[i] = oldTargetE


arr = [50, 40, 70, 60, 90]
index = [3, 0, 4, 1, 2]
n = len(arr)
reorder(arr, index, n)
print("Reordered array is:")
for i in range(0, n):
    print(arr[i], end=" ")
print("ModifiedIndexarrayis:")
for i in range(0, n):
    print(index[i], end=" ")

# Expected output:
Reordered array is:
40 60 90 50 70 ModifiedIndexarrayis:
0 1 2 3 4
# Stooge Sort | Function to implement stooge sort ; If first element is smaller than last , swap them ; If there are more than 2 elements in the array ; Recursively sort first 2 / 3 elements ; Recursively sort last 2 / 3 elements ; Recursively sort first 2 / 3 elements again to confirm ; deriver ; Calling Stooge Sort function to sort the array ; Display the sorted array
def stoogesort(arr, l, h):
    if l >= h:
        return
    if arr[l] > arr[h]:
        t = arr[l]
        arr[l] = arr[h]
        arr[h] = t
    if h - l + 1 > 2:
        t = (int)((h - l + 1) / 3)
        stoogesort(arr, l, (h - t))
        stoogesort(arr, l + t, (h))
        stoogesort(arr, l, (h - t))


arr = [2, 4, 5, 3, 1]
n = len(arr)
stoogesort(arr, 0, n - 1)
for i in range(0, n):
    print(arr[i], end=' ')

# Expected output:
1 2 3 4 5
# reorder an array according to given indexes | python3 code to reorder an array according to given indices ; left child in 0 based indexing ; right child in 1 based indexing ; find largest index from root , left and right child ; swap arr whenever index is swapped ; build heap ; swap the largest element of index ( first element ) with the last element ; swap arr whenever index is swapped ; 
def heapify(arr, index, i):
    largest = i
    left = 2 * i + 1
    right = 2 * i + 2
    global heapSize
    if (left < heapSize and index[left] > index[largest]):
        largest = left
    if (right < heapSize and index[right] > index[largest]):
        largest = right
    if (largest != i):
        arr[largest], arr[i] = arr[i], arr[largest]
        index[largest], index[i] = index[i], index[largest]
        heapify(arr, index, largest)


def heapSort(arr, index, n):
    global heapSize
    for i in range(int((n - 1) / 2), -1, -1):
        heapify(arr, index, i)
    for i in range(n - 1, 0, -1):
        index[0], index[i] = index[i], index[0]
        arr[0], arr[i] = arr[i], arr[0]
        heapSize -= 1
        heapify(arr, index, 0)


arr = [50, 40, 70, 60, 90]
index = [3, 0, 4, 1, 2]
n = len(arr)
global heapSize
heapSize = n
heapSort(arr, index, n)
print("Reordered array is: ")
print(*arr, sep=' ')
print("Modified Index array is: ")
print(*index, sep=' ')

# Expected output:
Reordered array is: 
40 60 90 50 70
Modified Index array is: 
0 1 2 3 4
# sort even | python3 program to sort even - placed elements in increasing and odd - placed in decreasing order with constant space complexity ; first odd index ; last index ; if last index is odd ; decrement j to even index ; swapping till half of array ; sort first half in increasing ; sort second half in decreasing ; 
def bitonicGenerator(arr, n):
    i = 1
    j = n - 1
    if (j % 2 != 0):
        j = j - 1
    while (i < j):
        arr[j], arr[i] = arr[i], arr[j]
        i = i + 2
        j = j - 2
    arr_f = []
    arr_s = []
    for i in range(int((n + 1) / 2)):
        arr_f .append(arr[i])
    i = int((n + 1) / 2)
    while (i < n):
        arr_s .append(arr[i])
        i = i + 1
    arr_f .sort()
    arr_s .sort(reverse=True)
    for i in arr_s:
        arr_f .append(i)
    return arr_f


arr = [1, 5, 8, 9, 6, 7, 3, 4, 2, 0]
n = len(arr)
arr = bitonicGenerator(arr, n)
print(arr)

# Expected output:
[1, 2, 3, 6, 8, 9, 7, 5, 4, 0]
# gnome sort | a function to sort the given list using gnome sort ; 
def gnomeSort(arr, n):
    index = 0
    while index < n:
        if index == 0:
            index = index + 1
        if arr[index] >= arr[index - 1]:
            index = index + 1
        else:
            arr[index], arr[index - 1] = arr[index - 1], arr[index]
            index = index - 1
    return arr


arr = [34, 2, 10, -9]
n = len(arr)
arr = gnomeSort(arr, n)
print("Sorted sequence after applying Gnome Sort :")
for i in arr:
    print(i)

# Expected output:
Sorted sequence after applying Gnome Sort :
-9
2
10
34
# cocktail sort | sorts arrar a [ 0. . n - 1 ] using cocktail sort ; reset the swapped flag on entering the loop , because it might be true from a previous iteration . ; loop from left to right same as the bubble sort ; if nothing moved , then array is sorted . ; otherwise , reset the swapped flag so that it can be used in the next stage ; move the end point back by one , because item at the end is in its rightful spot ; from right to left , doing the same comparison as in the previous stage ; increase the starting point , because the last stage would have moved the next smallest number to its rightful spot . ; 
def cocktailSort(a):
    n = len(a)
    swapped = True
    start = 0
    end = n - 1
    while (swapped):
        swapped = False
        for i in range(start, end):
            if (a[i] > a[i + 1]):
                a[i], a[i + 1] = a[i + 1], a[i]
                swapped = True
        if (swapped == False):
            break
        swapped = False
        end = end - 1
        for i in range(end - 1, start - 1, -1):
            if (a[i] > a[i + 1]):
                a[i], a[i + 1] = a[i + 1], a[i]
                swapped = True
        start = start + 1


a = [5, 1, 4, 2, 8, 0, 2]
cocktailSort(a)
print("Sorted array is:")
for i in range(len(a)):
    print("% d" % a[i])

# Expected output:
Sorted array is:
 0
 1
 2
 2
 4
 5
 8
# find the point where maximum intervals overlap | program to find maximum guest at any time in a party ; sort arrival and exit arrays ; guests_in indicates number of guests at a time ; similar to merge in merge sort to process all events in sorted order ; if next event in sorted order is arrival , increment count of guests ; update max_guests if needed ; increment index of arrival array ; if event is exit , decrement count ; of guests . ; 
def findMaxGuests(arrl, exit, n):
    arrl .sort()
    exit .sort()
    guests_in = 1
    max_guests = 1
    time = arrl[0]
    i = 1
    j = 0
    while (i < n and j < n):
        if (arrl[i] <= exit[j]):
            guests_in = guests_in + 1
            if (guests_in > max_guests):
                max_guests = guests_in
                time = arrl[i]
            i = i + 1
        else:
            guests_in = guests_in - 1
            j = j + 1
    print("Maximum Number of Guests =", max_guests, "at time", time)


arrl = [1, 2, 10, 5, 5]
exit = [4, 5, 12, 9, 12]
n = len(arrl)
findMaxGuests(arrl, exit, n)

# Expected output:
Maximum Number of Guests = 3 at time 5