giulio98/xlcost-single-prompt huggingface dataset:
# sort an array of dates in ascending order using custom comparator | python3 implementation to sort the array of dates in the form of " dd - mm - yyyy " using custom comparator ; comparator to sort the array of dates ; condition to check the year ; condition to check the month ; condition to check the day ; function that prints the dates in ascensding order ; sort the dates using library sort function with custom comparator ; loop to print the dates ; 

from functools import cmp_to_key


def myCompare(date1, date2):
    day1 = date1[0:2]
    month1 = date1[3:3 + 2]
    year1 = date1[6:6 + 4]
    day2 = date2[0:2]
    month2 = date2[3:3 + 2]
    year2 = date2[6:6 + 4]
    if (year1 < year2):
        return -1
    if (year1 > year2):
        return 1
    if (month1 < month2):
        return -1
    if (month1 > month2):
        return 1
    if (day1 < day2):
        return -1
    if (day1 > day2):
        return 1


def printDatesAscending(arr):
    arr = sorted(arr, key=cmp_to_key(lambda a, b: myCompare(a, b)))
    for i in range(len(arr)):
        print(arr[i])


arr = []
arr .append("25-08-1996")
arr .append("03-08-1970")
arr .append("09-04-1994")
arr .append("29-08-1996")
arr .append("14-02-1972")
printDatesAscending(arr)

# Expected output:
03-08-1970
14-02-1972
09-04-1994
25-08-1996
29-08-1996
# sort an array of strings according to the number of vowels in them | function to check the vowel ; returns count of vowels in str ; check for vowel ; function to sort the array according to the number of the vowels ; vector to store the number of vowels with respective elements ; inserting number of vowels with respective strings in the vector pair ; sort the vector , this will sort the pair according to the number of vowels ; print the sorted vector content ; 
def isVowel(ch):
    ch = ch .upper()
    return (ch == 'A' or ch == 'E' or ch == 'I' or ch == 'O' or ch == 'U')


def countVowels(string):
    count = 0
    for i in range(len(string)):
        if (isVowel(string[i])):
            count += 1
    return count


def sortArr(arr, n):
    vp = []
    for i in range(n):
        vp .append((countVowels(arr[i]), arr[i]))
    vp .sort()
    for i in range(len(vp)):
        print(vp[i][1], end=" ")


if __name__ == "__main__":
    arr = ["lmno", "pqrst", "aeiou", "xyz"]
    n = len(arr)
    sortArr(arr, n)

# Expected output:
pqrst xyz lmno aeiou
# find the minimum cost to cross the river | function to return the minimum cost ; sort the price array ; calculate minimum price of n - 2 most costly person ; both the ways as discussed above ; calculate the minimum price of the two cheapest person ; 
def minimumCost(price, n):
    price = sorted(price)
    totalCost = 0
    for i in range(n - 1, 1, -2):
        if (i == 2):
            totalCost += price[2] + price[0]
        else:
            price_first = price[i] + price[0] + 2 * price[1]
            price_second = price[i] + price[i - 1] + 2 * price[0]
            totalCost += min(price_first, price_second)
    if (n == 1):
        totalCost += price[0]
    else:
        totalCost += price[1]
    return totalCost


price = [30, 40, 60, 70]
n = len(price)
print(minimumCost(price, n))

# Expected output:
220
# minimize the sum of differences of consecutive elements after removing exactly k elements | python3 implementation of the above approach . ; states of dp ; function to find minimum sum ; base - case ; if state is solved before , return ; marking the state as solved ; recurrence relation ; 

import numpy as np
N = 100
INF = 1000000
dp = np .zeros((N, N))
vis = np .zeros((N, N))


def findSum(arr, n, k, l, r):
    if ((l) + (n - 1 - r) == k):
        return arr[r] - arr[l]
    if (vis[l][r]):
        return dp[l][r]
    vis[l][r] = 1
    dp[l][r] = min(findSum(arr, n, k, l, r - 1), findSum(arr, n, k, l + 1, r))
    return dp[l][r]


if __name__ == "__main__":
    arr = [1, 2, 100, 120, 140]
    k = 2
    n = len(arr)
    print(findSum(arr, n, k, 0, n - 1))

# Expected output:
40.0
# find kth element in an array containing odd elements first and then even elements | function to return the kth element in the modified array ; finding the index from where the even numbers will be stored ; return the kth element ; 
def getNumber(n, k):
    if (n % 2 == 0):
        pos = n // 2
    else:
        pos = (n // 2) + 1
    if (k <= pos):
        return (k * 2 - 1)
    else:
        return ((k - pos) * 2)


if __name__ == "__main__":
    n = 8
    k = 5
    print(getNumber(n, k))

# Expected output:
2
# find the longest string that can be made up of other strings from the array | function that returns true if string s can be made up of by other two string from the array after concatenating one after another ; if current string has been processed before ; if current string is found in the map and it is not the string under consideration ; split the string into two contiguous sub - strings ; if left sub - string is found in the map and the right sub - string can be made from the strings from the given array ; if everything failed , we return false ; function to return the longest string that can made be made up from the other string of the given array ; put all the strings in the map ; sort the string in decreasing order of their lengths ; starting from the longest string ; if current string can be made up from other strings ; 
def canbuildword(s, isoriginalword, mp):
    if s in mp and mp[s] == 0:
        return False
    if s in mp and mp[s] == 1 and isoriginalword == 0:
        return True
    for i in range(1, len(s)):
        left = s[:i]
        right = s[i:]
        if left in mp and mp[left] == 1 and canbuildword(right, 0, mp):
            return True
    mp[s] = 0
    return False


def printlongestword(listofwords):
    mp = dict()
    for i in listofwords:
        mp[i] = 1
    listofwords .sort(key=lambda x: len(x), reverse=True)
    for i in listofwords:
        if canbuildword(i, 1, mp):
            return i
    return "-1"


if __name__ == "__main__":
    listofwords = ["geeks", "for", "geeksfor", "geeksforgeeks"]
    print(printlongestword(listofwords))

# Expected output:
geeksforgeeks
# find a triplet in an array whose sum is closest to a given number | python3 implementation of the above approach ; function to return the sum of a triplet which is closest to x ; to store the closest sum ; run three nested loops each loop for each element of triplet ; update the closestsum ; return the closest sum found ; 

import sys


def solution(arr, x):
    closestSum = sys .maxsize
    for i in range(len(arr)):
        for j in range(i + 1, len(arr)):
            for k in range(j + 1, len(arr)):
                if (abs(x - closestSum) > abs(x - (arr[i] + arr[j] + arr[k]))):
                    closestSum = (arr[i] + arr[j] + arr[k])
    return closestSum


if __name__ == "__main__":
    arr = [-1, 2, 1, -4]
    x = 1
    print(solution(arr, x))

# Expected output:
2
# build original array from the given sub | python3 implementation of the approach ; function to add edge to graph ; function to calculate indegrees of all the vertices ; if there is an edge from i to x then increment indegree of x ; function to perform topological sort ; push every node to the queue which has no incoming edge ; since edge u is removed , update the indegrees of all the nodes which had an incoming edge from u ; function to generate the array from the given sub - sequences ; create the graph from the input sub - sequences ; add edge between every two consecutive elements of the given sub - sequences ; get the indegrees for all the vertices ; get the topological order of the created graph ; size of the required array ; 

from collections import deque
adj = [[]for i in range(100)]


def addEdge(u, v):
    adj[u].append(v)


def getindeg(V, indeg):
    for i in range(V):
        for x in adj[i]:
            indeg[x] += 1


def topo(V, indeg):
    q = deque()
    for i in range(V):
        if (indeg[i] == 0):
            q .appendleft(i)
    res = []
    while (len(q) > 0):
        u = q .popleft()
        res .append(u)
        for x in adj[u]:
            indeg[x] -= 1
            if (indeg[x] == 0):
                q .appendleft(x)
    return res


def makearray(v, V):
    for i in range(len(v)):
        for j in range(len(v[i]) - 1):
            addEdge(v[i][j], v[i][j + 1])
    indeg = [0 for i in range(V)]
    getindeg(V, indeg)
    res = topo(V, indeg)
    return res


n = 10
subseqs = [[9, 1, 2, 8, 3], [6, 1, 2], [9, 6, 3, 4], [5, 2, 7], [0, 9, 5, 4]]
res = makearray(subseqs, n)
for x in res:
    print(x, end=" ")

# Expected output:
0 9 5 6 1 2 7 8 3 4
# compress the array into ranges | function to compress the array ranges ; start iteration from the ith array element ; loop until arr [ i + 1 ] == arr [ i ] and increment j ; if the program do not enter into the above while loop this means that ( i + 1 ) th element is not consecutive to i th element ; increment i for next iteration ; print the consecutive range found ; move i jump directly to j + 1 ; 
def compressArr(arr, n):
    i = 0
    j = 0
    arr .sort()
    while (i < n):
        j = i
        while ((j + 1 < n) and (arr[j + 1] == arr[j] + 1)):
            j += 1
        if (i == j):
            print(arr[i], end=" ")
            i += 1
        else:
            print(arr[i], "-", arr[j], end=" ")
            i = j + 1


n = 7
arr = [1, 3, 4, 5, 6, 9, 10]
compressArr(arr, n)

# Expected output:
1 3 - 6 9 - 10
# remove elements to make array sorted | function to sort the array by removing misplaced elements ; brr [ ] is used to store the sorted array elements ; print the sorted array ; 
def removeElements(arr, n):
    brr = [0] * n
    l = 1
    brr[0] = arr[0]
    for i in range(1, n):
        if (brr[l - 1] <= arr[i]):
            brr[l] = arr[i]
            l += 1
    for i in range(l):
        print(brr[i], end=" ")


if __name__ == "__main__":
    arr = [10, 12, 9, 10, 2, 13, 14]
    n = len(arr)
    removeElements(arr, n)

# Expected output:
10 12 13 14
# remove elements to make array sorted | function to sort the array by removing misplaced elements ; l stores the index ; print the sorted array ; 
def removeElements(arr, n):
    l = 1
    for i in range(1, n):
        if (arr[l - 1] <= arr[i]):
            arr[l] = arr[i]
            l += 1
    for i in range(l):
        print(arr[i], end=" ")


if __name__ == "__main__":
    arr = [10, 12, 9, 10, 2, 13, 14]
    n = len(arr)
    removeElements(arr, n)

# Expected output:
10 12 13 14
# find number from its divisors | python3 implementation of the approach function that returns x ; function that returns x ; sort the given array ; get the possible x ; container to store divisors ; find the divisors of x ; check if divisor ; sort the vec because a is sorted and we have to compare all the elements ; if size of both vectors is not same then we are sure that both vectors can 't be equal ; check if a and vec have same elements in them ; 

import math


def findX(list, int):
    list .sort()
    x = list[0] * list[int - 1]
    vec = []
    i = 2
    while (i * i <= x):
        if (x % i == 0):
            vec .append(i)
            if ((x // i) != i):
                vec .append(x // i)
        i += 1
    vec .sort()
    if (len(vec) != int):
        return -1
    else:
        j = 0
        for it in range(int):
            if (a[j] != vec[it]):
                return -1
            else:
                j += 1
    return x


a = [2, 5, 4, 10]
n = len(a)
print(findX(a, n))

# Expected output:
20
# program to print an array in pendulum arrangement with constant space | function to print the pendulum arrangement of the given array ; sort the array ; pos stores the index of the last element of the array ; odd stores the last odd index in the array ; move all odd index positioned elements to the right ; shift the elements by one position from odd to pos ; reverse the element from 0 to ( n - 1 ) / 2 ; printing the pendulum arrangement ; 
def pendulumArrangement(arr, n):
    arr .sort(reverse=False)
    pos = n - 1
    if (n % 2 == 0):
        odd = n - 1
    else:
        odd = n - 2
    while (odd > 0):
        temp = arr[odd]
        in1 = odd
        while (in1 != pos):
            arr[in1] = arr[in1 + 1]
            in1 += 1
        arr[in1] = temp
        odd = odd - 2
        pos = pos - 1
    start = 0
    end = int((n - 1) / 2)
    while (start < end):
        temp = arr[start]
        arr[start] = arr[end]
        arr[end] = temp
        start += 1
        end -= 1
    for i in range(n):
        print(arr[i], end=" ")


if __name__ == '__main__':
    arr = [11, 2, 4, 55, 6, 8]
    n = len(arr)
    pendulumArrangement(arr, n)

# Expected output:
11 6 2 4 8 55
# minimum number greater than the maximum of array which cannot be formed using the numbers in the array | function that returns the minimum number greater than maximum of the array that cannot be formed using the elements of the array ; sort the given array ; maximum number in the array ; table [ i ] will store the minimum number of elements from the array to form i ; calculate the minimum number of elements from the array required to form the numbers from 1 to ( 2 * max ) ; if there exists a number greater than the maximum element of the array that can be formed using the numbers of array ; 
def findNumber(arr, n):
    arr = sorted(arr)
    Max = arr[n - 1]
    table = [10 ** 9 for i in range((2 * Max) + 1)]
    table[0] = 0
    ans = -1
    for i in range(1, 2 * Max + 1):
        for j in range(n):
            if (arr[j] <= i):
                res = table[i - arr[j]]
                if (res != 10 ** 9 and res + 1 < table[i]):
                    table[i] = res + 1
        if (i > arr[n - 1] and table[i] == 10 ** 9):
            ans = i
            break
    return ans


arr = [6, 7, 15]
n = len(arr)
print(findNumber(arr, n))

# Expected output:
16
# bitwise and of n binary strings | this function takes two unequal sized bit strings , converts them to same length by adding leading 0 s in the smaller string . returns the the new length ; return len_b which is highest . no need to proceed further ! ; return len_a which is greater or equal to len_b ; the main function that performs and operation of two - bit sequences and returns the resultant string ; make both strings of same length with the maximum length of s1 & s2 . ; initialize res as null string ; we start from left to right as we have made both strings of same length . ; convert s1 [ i ] and s2 [ i ] to int and perform bitwise and operation , append to " res " string ; 
def makeEqualLength(a, b):
    len_a = len(a)
    len_b = len(b)
    num_zeros = abs(len_a - len_b)
    if (len_a < len_b):
        for i in range(num_zeros):
            a = '0' + a
        return len_b, a, b
    else:
        for i in range(num_zeros):
            b = '0' + b
    return len_a, a, b


def andOperationBitwise(s1, s2):
    length, s1, s2 = makeEqualLength(s1, s2)
    res = ""
    for i in range(length):
        res = res + str(int(s1[i]) & int(s2[i]))
    return res


arr = ["101", "110110", "111"]
n = len(arr)
if (n < 2):
    print(arr[n - 1])
else:
    result = arr[0]
    for i in range(n):
        result = andOperationBitwise(result, arr[i])
    print(result)

# Expected output:
000100
# maximum number of segments that can contain the given points | function to return the maximum number of segments ; sort both the vectors ; initially pointing to the first element of b [ ] ; try to find a match in b [ ] ; the segment ends before b [ j ] ; the point lies within the segment ; the segment starts after b [ j ] ; return the required count ; 
def countPoints(n, m, a, b, x, y):
    a .sort()
    b .sort()
    j, count = 0, 0
    for i in range(0, n):
        while j < m:
            if a[i] + y < b[j]:
                break
            if (b[j] >= a[i] - x and b[j] <= a[i] + y):
                count += 1
                j += 1
                break
            else:
                j += 1
    return count


if __name__ == "__main__":
    x, y = 1, 4
    a = [1, 5]
    n = len(a)
    b = [1, 1, 2]
    m = len(b)
    print(countPoints(n, m, a, b, x, y))

# Expected output:
1
# merge k sorted arrays | set 3 ( using divide and conquer approach ) | python3 program to merge k sorted arrays ; merge and sort k arrays ; put the elements in sorted array . ; sort the output array ; 

N = 4


def merge_and_sort(output, arr, n, k):
    for i in range(k):
        for j in range(n):
            output[i * n + j] = arr[i][j]
    output .sort()


if __name__ == '__main__':
    arr = [[5, 7, 15, 18], [1, 8, 9, 17], [1, 4, 7, 7]]
    n = N
    k = len(arr)
    output = [0 for i in range(n * k)]
    merge_and_sort(output, arr, n, k)
    for i in range(n * k):
        print(output[i], end=' ')

# Expected output:
1 1 4 5 7 7 7 8 9 15 17 18
# minimum operations of given type to make all elements of a matrix equal | function to return the minimum number of operations required ; create another array to store the elements of matrix ; will not work for negative elements , so . . adding this ; adding this to handle negative elements too . ; sort the array to get median ; to count the minimum operations ; if there are even elements , then there are two medians . we consider the best of two as answer . ; changed here as in case of even elements there will be 2 medians ; return minimum operations required ; 
def minOperations(n, m, k, matrix):
    arr = []
    if (matrix[0][0] < 0):
        mod = k - (abs(matrix[0][0]) % k)
    else:
        mod = matrix[0][0] % k
    for i in range(n):
        for j in range(m):
            arr .append(matrix[i][j])
            val = matrix[i][j]
            if (val < 0):
                res = k - (abs(val) % k)
                if (res != mod):
                    return -1
            else:
                foo = matrix[i][j]
                if (foo % k != mod):
                    return -1
    arr .sort()
    median = arr[(n * m) // 2]
    minOperations = 0
    for i in range(n * m):
        minOperations += abs(arr[i] - median) // k
    if ((n * m) % 2 == 0):
        median2 = arr[((n * m) // 2) - 1]
        minOperations2 = 0
        for i in range(n * m):
            minOperations2 += abs(arr[i] - median2) / k
        minOperations = min(minOperations, minOperations2)
    return minOperations


if __name__ == "__main__":
    matrix = [[2, 4, 6], [8, 10, 12], [14, 16, 18], [20, 22, 24]]
    n = len(matrix)
    m = len(matrix[0])
    k = 2
    print(minOperations(n, m, k, matrix))

# Expected output:
36
# smallest subarray containing minimum and maximum values | python3 implementation of above approach ; function to return length of smallest subarray containing both maximum and minimum value ; find maximum and minimum values in the array ; iterate over the array and set answer to smallest difference between position of maximum and position of minimum value ; last occurrence of minvalue ; last occurrence of maxvalue ; 

import sys


def minSubarray(A, n):
    minValue = min(A)
    maxValue = max(A)
    pos_min, pos_max, ans = -1, -1, sys .maxsize
    for i in range(0, n):
        if A[i] == minValue:
            pos_min = i
        if A[i] == maxValue:
            pos_max = i
        if pos_max != -1 and pos_min != -1:
            ans = min(ans, abs(pos_min - pos_max) + 1)
    return ans


A = [1, 5, 9, 7, 1, 9, 4]
n = len(A)
print(minSubarray(A, n))

# Expected output:
2
# minimum number of consecutive sequences that can be formed in an array | python3 program find the minimum number of consecutive sequences in an array ; 
def countSequences(arr, n):
    count = 1
    arr .sort()
    for i in range(n - 1):
        if (arr[i] + 1 != arr[i + 1]):
            count += 1
    return count


if __name__ == "__main__":
    arr = [1, 7, 3, 5, 10]
    n = len(arr)
    print(countSequences(arr, n))

# Expected output:
5
# minimum number of increment / decrement operations such that array contains all elements from 1 to n | function to find the minimum operations ; sort the given array ; count operations by assigning a [ i ] = i + 1 ; 
def minimumMoves(a, n):
    operations = 0
    a .sort(reverse=False)
    for i in range(0, n, 1):
        operations = operations + abs(a[i] - (i + 1))
    return operations


if __name__ == '__main__':
    arr = [5, 3, 2]
    n = len(arr)
    print(minimumMoves(arr, n))

# Expected output:
4
# print a case where the given sorting algorithm fails | function to print a case where the given sorting algorithm fails ; only case where it fails ; 
def printCase(n):
    if (n <= 2):
        print("-1")
        return
    for i in range(n, 0, -1):
        print(i, end=" ")


if __name__ == "__main__":
    n = 3
    printCase(n)

# Expected output:
3 2 1
# find the missing elements from 1 to m in given n ranges | function to find missing elements from given ranges ; first of all sort all the given ranges ; store ans in a different vector ; prev is use to store end of last range ; j is used as a counter for ranges ; for last segment ; finally print all answer ; 
def findMissingNumber(ranges, m):
    ranges .sort()
    ans = []
    prev = 0
    for j in range(len(ranges)):
        start = ranges[j][0]
        end = ranges[j][1]
        for i in range(prev + 1, start):
            ans .append(i)
        prev = end
    for i in range(prev + 1, m + 1):
        ans .append(i)
    for i in range(len(ans)):
        if ans[i] <= m:
            print(ans[i], end=" ")


if __name__ == "__main__":
    N, M = 2, 6
    ranges = []
    ranges .append([1, 2])
    ranges .append([4, 5])
    findMissingNumber(ranges, M)

# Expected output:
3 6
# check whether it is possible to make both arrays equal by modifying a single element | function to check if both sequences can be made equal ; sorting both the arrays ; flag to tell if there are more than one mismatch ; to stores the index of mismatched element ; if there is more than one mismatch then return false ; if there is no mismatch or the difference between the mismatching elements is <= k then return true ; 
def check(n, k, a, b):
    a .sort()
    b .sort()
    fl = False
    ind = -1
    for i in range(n):
        if (a[i] != b[i]):
            if (fl):
                return False
            fl = True
            ind = i
    if (ind == -1 or abs(a[ind] - b[ind]) <= k):
        return True
    return False


n, k = 2, 4
a = [1, 5]
b = [1, 1]
if (check(n, k, a, b)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# sum of width ( max and min diff ) of all subsequences | function to return sum of width of all subsets ; sort the array ; 
def SubseqWidths(A):
    MOD = 10 ** 9 + 7
    N = len(A)
    A .sort()
    pow2 = [1]
    for i in range(1, N):
        pow2 .append(pow2[-1] * 2 % MOD)
    ans = 0
    for i, x in enumerate(A):
        ans = (ans + (pow2[i] - pow2[N - 1 - i]) * x) % MOD
    return ans


A = [5, 6, 4, 3, 8]
print(SubseqWidths(A))

# Expected output:
87
# covering maximum array elements with given value | function to find value for covering maximum array elements ; sort the students in ascending based on the candies ; to store the number of happy students ; to store the running sum ; if the current student can 't be made happy ; increment the count if we can make the ith student happy ; if the sum = x then answer is n ; if the count is equal to n then the answer is n - 1 ; 
def maxArrayCover(a, n, x):
    a .sort()
    cc = 0
    s = 0
    for i in range(n):
        s += a[i]
        if (s > x):
            break
        cc += 1
    if (sum(a) == x):
        return n
    else:
        if (cc == n):
            return n - 1
        else:
            return cc


if __name__ == '__main__':
    n, x = 3, 70
    a = [10, 20, 30]
    print(maxArrayCover(a, n, x))

# Expected output:
2
# maximum sum of products of two arrays | function that calculates maximum sum of products of two arrays ; variable to store the sum of products of array elements ; length of the arrays ; sorting both the arrays ; traversing both the arrays and calculating sum of product ; 
def maximumSOP(a, b):
    sop = 0
    n = len(a)
    a .sort()
    b .sort()
    for i in range(n):
        sop += a[i] * b[i]
    return sop


if __name__ == "__main__":
    A = [1, 2, 3]
    B = [4, 5, 1]
    print(maximumSOP(A, B))

# Expected output:
24