giulio98/xlcost-single-prompt huggingface dataset:
# count strictly increasing subarrays | python3 program to count number of strictlyincreasing subarrays in o ( n ) time . ; initialize result ; initialize length of current increasing subarray ; traverse through the array ; if arr [ i + 1 ] is greater than arr [ i ] , then increment length ; else update count and reset length ; if last length is more than 1 ; 
def countIncreasing(arr, n):
    cnt = 0
    len = 1
    for i in range(0, n - 1):
        if arr[i + 1] > arr[i]:
            len += 1
        else:
            cnt += (((len - 1) * len) / 2)
            len = 1
    if len > 1:
        cnt += (((len - 1) * len) / 2)
    return cnt


arr = [1, 2, 2, 4]
n = len(arr)
print("Count of strictly increasing subarrays is", int(countIncreasing(arr, n)))

# Expected output:
Count of strictly increasing subarrays is 2
# maximum difference between group of k | utility function for array sum ; function for finding maximum group difference of array ; sort the array ; find array sum ; difference for k - smallest diff1 = ( arraysum - k_smallest ) - k_smallest ; reverse array for finding sum 0f 1 st k - largest ; difference for k - largest diff2 = ( arraysum - k_largest ) - k_largest ; return maximum difference value ; 
def arraySum(arr, n):
    sum = 0
    for i in range(n):
        sum = sum + arr[i]
    return sum


def maxDiff(arr, n, k):
    arr .sort()
    arraysum = arraySum(arr, n)
    diff1 = abs(arraysum - 2 * arraySum(arr, k))
    arr .reverse()
    diff2 = abs(arraysum - 2 * arraySum(arr, k))
    return (max(diff1, diff2))


if __name__ == "__main__":
    arr = [1, 7, 4, 8, -1, 5, 2, 1]
    n = len(arr)
    k = 3
    print("Maximum Difference =", maxDiff(arr, n, k))

# Expected output:
Maximum Difference = 25
# minimum number of elements to add to make median equals x | returns count of elements to be added to make median x . this function assumes that a [ ] has enough extra space . ; to sort the array in increasing order . ; 
def minNumber(a, n, x):
    a .sort(reverse=False)
    k = 0
    while (a[int((n - 1) / 2)] != x):
        a[n - 1] = x
        n += 1
        a .sort(reverse=False)
        k += 1
    return k


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

# Expected output:
1
# minimum number of elements to add to make median equals x | python3 program to find minimum number of elements to add so that its median equals x . ; no . of elements equals to x , that is , e . ; no . of elements greater than x , that is , h . ; no . of elements smaller than x , that is , l . ; subtract the no . of elements that are equal to x . ; 
def minNumber(a, n, x):
    l = 0
    h = 0
    e = 0
    for i in range(n):
        if a[i] == x:
            e += 1
        elif a[i] > x:
            h += 1
        elif a[i] < x:
            l += 1
    ans = 0
    if l > h:
        ans = l - h
    elif l < h:
        ans = h - l - 1
    return ans + 1 - e


x = 10
a = [10, 20, 30]
n = len(a)
print(minNumber(a, n, x))

# Expected output:
1
# check in binary array the number represented by a subarray is odd or even | prints if subarray is even or odd ; if arr [ r ] = 1 print odd ; if arr [ r ] = 0 print even ; 
def checkEVENodd(arr, n, l, r):
    if (arr[r] == 1):
        print("odd")
    else:
        print("even")


arr = [1, 1, 0, 1]
n = len(arr)
checkEVENodd(arr, n, 1, 3)

# Expected output:
odd
# mean of range in array | python 3 program to find floor value of mean in range l to r ; to find mean of range in l to r ; both sum and count are initialize to 0 ; to calculate sum and number of elements in range l to r ; calculate floor value of mean ; returns mean of array in range l to r ; 

import math


def findMean(arr, l, r):
    sum, count = 0, 0
    for i in range(l, r + 1):
        sum += arr[i]
        count += 1
    mean = math .floor(sum / count)
    return mean


arr = [1, 2, 3, 4, 5]
print(findMean(arr, 0, 2))
print(findMean(arr, 1, 3))
print(findMean(arr, 0, 4))

# Expected output:
2
3
3
# products of ranges in an array | function to calculate product in the given range . ; as our array is 0 based and l and r are given as 1 based index . ; 
def calculateProduct(A, L, R, P):
    L = L - 1
    R = R - 1
    ans = 1
    for i in range(R + 1):
        ans = ans * A[i]
        ans = ans % P
    return ans


A = [1, 2, 3, 4, 5, 6]
P = 229
L = 2
R = 5
print(calculateProduct(A, L, R, P))
L = 1
R = 3
print(calculateProduct(A, L, R, P))

# Expected output:
120
6
# no of pairs ( a [ j ] >= a [ i ] ) with k numbers in range ( a [ i ] , a [ j ] ) that are divisible by x | python3 program to calculate the number pairs satisfying th condition ; function to calculate the number of pairs ; traverse through all elements ; current number 's divisor ; use binary search to find the element after k multiples of x ; use binary search to find the element after k + 1 multiples of x so that we get the answer bu subtracting ; the difference of index will be the answer ; 

import bisect


def countPairs(a, n, x, k):
    a .sort()
    ans = 0
    for i in range(n):
        d = (a[i] - 1) // x
        it1 = bisect .bisect_left(a, max((d + k) * x, a[i]))
        it2 = bisect .bisect_left(a, max((d + k + 1) * x, a[i]))
        ans += it2 - it1
    return ans


if __name__ == "__main__":
    a = [1, 3, 5, 7]
    n = len(a)
    x = 2
    k = 1
    print(countPairs(a, n, x, k))

# Expected output:
3
# probability of a random pair being the maximum weighted pair |  ; function to return probability ; count occurrences of maximum element in a [ ] ; count occurrences of maximum element in b [ ] ; returning probability ; 

import sys


def probability(a, b, size1, size2):
    max1 = -(sys .maxsize - 1)
    count1 = 0
    for i in range(size1):
        if a[i] > max1:
            count1 = 1
        elif a[i] == max1:
            count1 += 1
    max2 = -(sys .maxsize - 1)
    count2 = 0
    for i in range(size2):
        if b[i] > max2:
            max2 = b[i]
            count2 = 1
        elif b[i] == max2:
            count2 += 1
    return round((count1 * count2) / (size1 * size2), 6)


a = [1, 2, 3]
b = [1, 3, 3]
size1 = len(a)
size2 = len(b)
print(probability(a, b, size1, size2))

# Expected output:
0.222222
# minimum de | function to count dearrangement ; create a copy of original array ; sort the array ; traverse sorted array for counting mismatches ; reverse the sorted array ; traverse reverse sorted array for counting mismatches ; return minimum mismatch count ; 
def countDe(arr, n):
    i = 0
    v = arr .copy()
    arr .sort()
    count1 = 0
    i = 0
    while (i < n):
        if (arr[i] != v[i]):
            count1 = count1 + 1
        i = i + 1
    arr .sort(reverse=True)
    count2 = 0
    i = 0
    while (i < n):
        if (arr[i] != v[i]):
            count2 = count2 + 1
        i = i + 1
    return (min(count1, count2))


arr = [5, 9, 21, 17, 13]
n = 5
print("Minimum Dearrangement =", countDe(arr, n))

# Expected output:
Minimum Dearrangement = 2
# divide an array into k segments to maximize maximum of segment minimums | function to calculate the max of all the minimum segments ; if we have to divide it into 1 segment then the min will be the answer ; if k >= 3 , return maximum of all elements . ; 
def maxOfSegmentMins(a, n, k):
    if k == 1:
        return min(a)
    if k == 2:
        return max(a[0], a[n - 1])
    return max(a)


if __name__ == '__main__':
    a = [-10, -9, -8, 2, 7, -6, -5]
    n = len(a)
    k = 2
    print(maxOfSegmentMins(a, n, k))

# Expected output:
-5
# minimum product pair an array of positive integers | function to calculate minimum product of pair ; initialize first and second minimums . it is assumed that the array has at least two elements . ; traverse remaining array and keep track of two minimum elements ( note that the two minimum elements may be same if minimum element appears more than once ) more than once ) ; 
def printMinimumProduct(arr, n):
    first_min = min(arr[0], arr[1])
    second_min = max(arr[0], arr[1])
    for i in range(2, n):
        if (arr[i] < first_min):
            second_min = first_min
            first_min = arr[i]
        elif (arr[i] < second_min):
            second_min = arr[i]
    return first_min * second_min


a = [11, 8, 5, 7, 5, 100]
n = len(a)
print(printMinimumProduct(a, n))

# Expected output:
25
# count ways to form minimum product triplets | function to calculate number of triples ; sort the array ; count occurrences of third element ; if all three elements are same ( minimum element appears at l east 3 times ) . answer is nc3 . ; if minimum element appears once . answer is nc2 . ; minimum two elements are distinct . answer is nc1 . ; 
def noOfTriples(arr, n):
    arr .sort()
    count = 0
    for i in range(n):
        if arr[i] == arr[2]:
            count += 1
    if arr[0] == arr[2]:
        return (count - 2) * (count - 1) * (count) / 6
    elif arr[1] == arr[2]:
        return (count - 1) * (count) / 2
    return count


arr = [1, 3, 3, 4]
n = len(arr)
print(noOfTriples(arr, n))

# Expected output:
1.0
# check if reversing a sub array make the array sorted | return true , if reversing the subarray will sort the array , else return false . ; copying the array ; sort the copied array . ; finding the first mismatch . ; finding the last mismatch . ; if whole array is sorted ; checking subarray is decreasing or not . ; 
def checkReverse(arr, n):
    temp = [0] * n
    for i in range(n):
        temp[i] = arr[i]
    temp .sort()
    for front in range(n):
        if temp[front] != arr[front]:
            break
    for back in range(n - 1, -1, -1):
        if temp[back] != arr[back]:
            break
    if front >= back:
        return True
    while front != back:
        front += 1
        if arr[front - 1] < arr[front]:
            return False
    return True


arr = [1, 2, 5, 4, 3]
n = len(arr)
if checkReverse(arr, n):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# check if reversing a sub array make the array sorted | python3 program to check whether reversing a sub array make the array sorted or not ; return true , if reversing the subarray will sort the array , else return false . ; find first increasing part ; find reversed part ; find last increasing part ; to handle cases like 1 , 2 , 3 , 4 , 20 , 9 , 16 , 17 ; 

import math as mt


def checkReverse(arr, n):
    if (n == 1):
        return True
    i = 1
    for i in range(1, n):
        if arr[i - 1] < arr[i]:
            if (i == n):
                return True
        else:
            break
    j = i
    while (j < n and arr[j] < arr[j - 1]):
        if (i > 1 and arr[j] < arr[i - 2]):
            return False
        j += 1
    if (j == n):
        return True
    k = j
    if (arr[k] < arr[i - 1]):
        return False
    while (k > 1 and k < n):
        if (arr[k] < arr[k - 1]):
            return False
        k += 1
    return True


arr = [1, 3, 4, 10, 9, 8]
n = len(arr)
if checkReverse(arr, n):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# making elements of two arrays same with minimum increment / decrement | python 3 program to find minimum increment / decrement operations to make array elements same . ; sorting both arrays in ascending order ; variable to store the final result ; after sorting both arrays . now each array is in non - decreasing order . thus , we will now compare each element of the array and do the increment or decrement operation depending upon the value of array b [ ] . ; 
def MinOperation(a, b, n):
    a .sort(reverse=False)
    b .sort(reverse=False)
    result = 0
    for i in range(0, n, 1):
        if (a[i] > b[i]):
            result = result + abs(a[i] - b[i])
        elif (a[i] < b[i]):
            result = result + abs(a[i] - b[i])
    return result


if __name__ == '__main__':
    a = [3, 1, 1]
    b = [1, 2, 2]
    n = len(a)
    print(MinOperation(a, b, n))

# Expected output:
2
# sorting array except elements in a subarray | sort whole array a [ ] except elements in range a [ l . . r ] ; copy all those element that need to be sorted to an auxiliary array b [ ] ; sort the array b ; copy sorted elements back to a [ ] ; 
def sortExceptUandL(a, l, u, n):
    b = [0] * (n - (u - l + 1))
    for i in range(0, l):
        b[i] = a[i]
    for i in range(u + 1, n):
        b[l + (i - (u + 1))] = a[i]
    b .sort()
    for i in range(0, l):
        a[i] = b[i]
    for i in range(u + 1, n):
        a[i] = b[l + (i - (u + 1))]


a = [5, 4, 3, 12, 14, 9]
n = len(a)
l = 2
u = 4
sortExceptUandL(a, l, u, n)
for i in range(0, n):
    print("{} ".format(a[i]), end="")

# Expected output:
4 5 3 12 14 9
# sorting all array elements except one | python3 program to sort all elements except element at index k . ; move k - th element to end ; sort all elements except last ; store last element ( originally k - th ) ; move all elements from k - th to one position ahead . ; restore k - th element ; 
def sortExcept(arr, k, n):
    arr[k], arr[-1] = arr[-1], arr[k]
    arr = sorted(arr, key=lambda i: (i is arr[-1], i))
    last = arr[-1]
    i = n - 1
    while i > k:
        arr[i] = arr[i - 1]
        i -= 1
    arr[k] = last
    return arr


if __name__ == '__main__':
    a = [10, 4, 11, 7, 6, 20]
    k = 2
    n = len(a)
    a = sortExcept(a, k, n)
    print(" ".join(list(map(str, a))))

# Expected output:
4 6 11 7 10 20
# maximum number of partitions that can be sorted individually to make sorted | function to find maximum partitions . ; find maximum in prefix arr [ 0. . i ] ; if maximum so far is equal to index , we can make a new partition ending at index i . ; 
def maxPartitions(arr, n):
    ans = 0
    max_so_far = 0
    for i in range(0, n):
        max_so_far = max(max_so_far, arr[i])
        if (max_so_far == i):
            ans += 1
    return ans


arr = [1, 0, 2, 3, 4]
n = len(arr)
print(maxPartitions(arr, n))

# Expected output:
4
# rank of all elements in an array | python code to find rank of elements ; rank vector ; sweep through all elements in a for each element count the number of less than and equal elements separately in r and s . ; use formula to obtain rank ; 
def rankify(A):
    R = [0 for x in range(len(A))]
    for i in range(len(A)):
        (r, s) = (1, 1)
        for j in range(len(A)):
            if j != i and A[j] < A[i]:
                r += 1
            if j != i and A[j] == A[i]:
                s += 1
        R[i] = r + (s - 1) / 2
    return R


if __name__ == "__main__":
    A = [1, 2, 5, 2, 1, 25, 2]
    print(A)
    print(rankify(A))

# Expected output:
[1, 2, 5, 2, 1, 25, 2]
[1.5, 4.0, 6.0, 4.0, 1.5, 7.0, 4.0]
# minimum number of subtract operation to make an array decreasing | function to count minimum no of operation ; count how many times we have to subtract . ; check an additional subtraction is required or not . ; modify the value of arr [ i ] . ; count total no of operation / subtraction . ; 
def min_noOf_operation(arr, n, k):
    res = 0
    for i in range(1, n):
        noOfSubtraction = 0
        if (arr[i] > arr[i - 1]):
            noOfSubtraction = (arr[i] - arr[i - 1]) / k
            if ((arr[i] - arr[i - 1]) % k != 0):
                noOfSubtraction += 1
            arr[i] = arr[i] - k * noOfSubtraction
        res = res + noOfSubtraction
    return int(res)


arr = [1, 1, 2, 3]
N = len(arr)
k = 5
print(min_noOf_operation(arr, N, k))

# Expected output:
3
# maximize the sum of arr [ i ] * i | python program to find the maximum value of i * arr [ i ] ; sort the array ; finding the sum of arr [ i ] * i ; 
def maxSum(arr, n):
    arr .sort()
    sum = 0
    for i in range(n):
        sum += arr[i] * i
    return sum


arr = [3, 5, 6, 1]
n = len(arr)
print(maxSum(arr, n))

# Expected output:
31
# pairs with difference less than k | function to count pairs ; 
def countPairs(a, n, k):
    res = 0
    for i in range(n):
        for j in range(i + 1, n):
            if (abs(a[j] - a[i]) < k):
                res += 1
    return res


a = [1, 10, 4, 2]
k = 3
n = len(a)
print(countPairs(a, n, k), end="")

# Expected output:
2
# pairs with difference less than k | python code to find count of pairs with difference less than k . ; to sort the array ; keep incrementing result while subsequent elements are within limits . ; 
def countPairs(a, n, k):
    a .sort()
    res = 0
    for i in range(n):
        j = i + 1
        while (j < n and a[j] - a[i] < k):
            res += 1
            j += 1
    return res


a = [1, 10, 4, 2]
k = 3
n = len(a)
print(countPairs(a, n, k), end="")

# Expected output:
2
# merging two unsorted arrays in sorted order | function to merge array in sorted order ; sorting a [ ] and b [ ] ; merge two sorted arrays into res [ ] ; merging remaining elements of a [ ] ( if any ) ; merging remaining elements of b [ ] ( if any ) ; 
def sortedMerge(a, b, res, n, m):
    a .sort()
    b .sort()
    i, j, k = 0, 0, 0
    while (i < n and j < m):
        if (a[i] <= b[j]):
            res[k] = a[i]
            i += 1
            k += 1
        else:
            res[k] = b[j]
            j += 1
            k += 1
    while (i < n):
        res[k] = a[i]
        i += 1
        k += 1
    while (j < m):
        res[k] = b[j]
        j += 1
        k += 1


a = [10, 5, 15]
b = [20, 3, 2, 12]
n = len(a)
m = len(b)
res = [0 for i in range(n + m)]
sortedMerge(a, b, res, n, m)
print("Sorted merged list :")
for i in range(n + m):
    print(res[i],)

# Expected output:
Sorted merged list :
2
3
5
10
12
15
20
# maximizing unique pairs from two arrays | returns count of maximum pairs that can be formed from a [ ] and b [ ] under given constraints . ; sorting the first array . ; sorting the second array . ; to keep track of visited elements of b [ ] ; for every element of a [ ] , find a pair for it and break as soon as a pair is found . ; increasing the count if a pair is formed . ; making the corresponding flag array element as 1 indicating the element in the second array element has been used . ; we break the loop to make sure an element of a [ ] is used only once . ; 
def findMaxPairs(a, b, n, k):
    a .sort()
    b .sort()
    flag = [False] * n
    result = 0
    for i in range(n):
        for j in range(n):
            if (abs(a[i] - b[j]) <= k and flag[j] == False):
                result += 1
                flag[j] = True
                break
    return result


if __name__ == "__main__":
    a = [10, 15, 20]
    b = [17, 12, 24]
    n = len(a)
    k = 3
    print(findMaxPairs(a, b, n, k))

# Expected output:
2
# maximizing unique pairs from two arrays | returns count of maximum pairs that caan be formed from a [ ] and b [ ] under given constraints . ; sorting the first array . ; sorting the second array . ; increasing array pointer of both the first and the second array . ; increasing array pointer of the second array . ; 
def findMaxPairs(a, b, n, k):
    a .sort()
    b .sort()
    result = 0
    j = 0
    for i in range(n):
        if j < n:
            if abs(a[i] - b[j]) <= k:
                result += 1
                j += 1
            elif a[i] > b[j]:
                j += 1
    return result


if __name__ == '__main__':
    a = [10, 15, 20]
    b = [17, 12, 24]
    n = len(a)
    k = 3
    print(findMaxPairs(a, b, n, k))

# Expected output:
2
# sum of minimum absolute difference of each array element | function to find the sum of minimum absolute difference ; sort the given array ; initialize sum ; min absolute difference for the 1 st array element ; min absolute difference for the last array element ; find min absolute difference for rest of the array elements and add them to sum ; required sum ; 
def sumOfMinAbsDifferences(arr, n):
    arr .sort()
    sum = 0
    sum += abs(arr[0] - arr[1])
    sum += abs(arr[n - 1] - arr[n - 2])
    for i in range(1, n - 1):
        sum += min(abs(arr[i] - arr[i - 1]), abs(arr[i] - arr[i + 1]))
    return sum


arr = [5, 10, 1, 4, 8, 7]
n = len(arr)
print("Sum = ", sumOfMinAbsDifferences(arr, n))

# Expected output:
Sum =  9
# smallest difference pair of values between two unsorted arrays | python 3 code to find smallest difference between two arrays ; function to calculate small result between two arrays ; sort both arrays using sort function ; initialize result as max value ; scan both arrays upto sizeof of the arrays ; move smaller value ; return final sma result ; input given array a ; input 

import sys


def findSmallestDifference(A, B, m, n):
    A .sort()
    B .sort()
    a = 0
    b = 0
    result = sys .maxsize
    while (a < m and b < n):
        if (abs(A[a] - B[b]) < result):
            result = abs(A[a] - B[b])
        if (A[a] < B[b]):
            a += 1
        else:
            b += 1
    return result


A = [1, 2, 11, 5]
B = [4, 12, 19, 23, 127, 235]
m = len(A)
n = len(B)
print(findSmallestDifference(A, B, m, n))

# Expected output:
1
# find the element that appears once in an array where every other element appears twice | singleelement function ; 
def singleelement(arr, n):
    low = 0
    high = n - 2
    mid = 0
    while (low <= high):
        mid = (low + high) // 2
        if (arr[mid] == arr[mid ^ 1]):
            low = mid + 1
        else:
            high = mid - 1
    return arr[low]


arr = [2, 3, 5, 4, 5, 3, 4]
size = len(arr)
arr .sort()
print(singleelement(arr, size))

# Expected output:
2
# count triplets with sum smaller than a given value | a simple python 3 program to count triplets with sum smaller than a given value include < bits / stdc ++ . h > ; initialize result ; fix the first element as a [ i ] ; fix the second element as a [ j ] ; now look for the third number ; 
def countTriplets(arr, n, sum):
    ans = 0
    for i in range(0, n - 2):
        for j in range(i + 1, n - 1):
            for k in range(j + 1, n):
                if (arr[i] + arr[j] + arr[k] < sum):
                    ans += 1
    return ans


arr = [5, 1, 3, 4, 7]
n = len(arr)
sum = 12
print(countTriplets(arr, n, sum))

# Expected output:
4
# count triplets with sum smaller than a given value | python3 program to count triplets with sum smaller than a given value ; sort input array ; initialize result ; every iteration of loop counts triplet with first element as arr [ i ] . ; initialize other two elements as corner elements of subarray arr [ j + 1. . k ] ; use meet in the middle concept ; if sum of current triplet is more or equal , move right corner to look for smaller values ; else move left corner ; this is important . for current i and j , there can be total k - j third elements . ; 
def countTriplets(arr, n, sum):
    arr .sort()
    ans = 0
    for i in range(0, n - 2):
        j = i + 1
        k = n - 1
        while (j < k):
            if (arr[i] + arr[j] + arr[k] >= sum):
                k = k - 1
            else:
                ans += (k - j)
                j = j + 1
    return ans


if __name__ == '__main__':
    arr = [5, 1, 3, 4, 7]
    n = len(arr)
    sum = 12
    print(countTriplets(arr, n, sum))

# Expected output:
4
# number of unique triplets whose xor is zero | function to count the number of unique triplets whose xor is 0 ; to store values that are present ; stores the count of unique triplets ; traverse for all i , j pairs such that j > i ; xor of a [ i ] and a [ j ] ; if xr of two numbers is present , then increase the count ; returns answer ; 
def countTriplets(a, n):
    s = set()
    for i in range(n):
        s .add(a[i])
    count = 0
    for i in range(n):
        for j in range(i + 1, n, 1):
            xr = a[i] ^ a[j]
            if (xr in s and xr != a[i] and xr != a[j]):
                count += 1
    return int(count / 3)


if __name__ == '__main__':
    a = [1, 3, 5, 10, 14, 15]
    n = len(a)
    print(countTriplets(a, n))

# Expected output:
2
# find the missing number | getmissingno takes list as argument ; 
def getMissingNo(A):
    n = len(A)
    total = (n + 1) * (n + 2) / 2
    sum_of_A = sum(A)
    return total - sum_of_A


A = [1, 2, 4, 5, 6]
miss = getMissingNo(A)
print(miss)

# Expected output:
3.0
# find the missing number | a represents the array n : number of elements in array a ; 
def getMissingNo(a, n):
    i, total = 0, 1
    for i in range(2, n + 2):
        total += i
        total -= a[i - 2]
    return total


arr = [1, 2, 3, 5]
print(getMissingNo(arr, len(arr)))

# Expected output:
4