giulio98/xlcost-single-prompt huggingface dataset:
# find the non decreasing order array from given array | python 3 implementation of the approach ; utility function to print the contents of the array ; function to build array b [ ] ; lower and upper limits ; to store the required array ; apply greedy approach ; print the built array b [ ] ; 

import sys


def printArr(b, n):
    for i in range(0, n, 1):
        print(b[i], end=" ")


def ModifiedArray(a, n):
    l = 0
    r = sys .maxsize
    b = [0 for i in range(n)]
    for i in range(0, int(n / 2), 1):
        b[i] = max(l, a[i] - r)
        b[n - i - 1] = a[i] - b[i]
        l = b[i]
        r = b[n - i - 1]
    printArr(b, n)


if __name__ == '__main__':
    a = [5, 6]
    n = len(a)
    ModifiedArray(a, 2 * n)

# Expected output:
0 1 5 5
# count of lines required to write the given string | function to return the number of lines required ; if string is empty ; initialize lines and width ; iterate through s ; return lines and width used ; 
def numberOfLines(S, widths):
    if (S == ""):
        return 0, 0
    lines, width = 1, 0
    for c in S:
        w = widths[ord(c) - ord('a')]
        width += w
        if width > 10:
            lines += 1
            width = w
    return lines, width


S = "bbbcccdddaa"
Widths = [4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
          1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
print(numberOfLines(S, Widths))

# Expected output:
(2, 8)
# check if elements of an array can be arranged satisfying the given condition | python implementation of the approach ; function to return true if the elements can be arranged in the desired order ; if 2 * x is not found to pair ; remove an occurrence of x and an occurrence of 2 * x ; 

import collections


def canReorder(A):
    count = collections .Counter(A)
    for x in sorted(A, key=abs):
        if count[x] == 0:
            continue
        if count[2 * x] == 0:
            return False
        count[x] -= 1
        count[2 * x] -= 1
    return True


A = [4, -2, 2, -4]
print(canReorder(A))

# Expected output:
True
# maximum sum of all elements of array after performing given operations | python3 program to find the maximum sum after given operations ; function to calculate maximum subarray sum or kadane 's algorithm ; function to find the maximum sum after given operations ; to store sum of all elements ; maximum sum of a subarray ; calculate the sum of all elements ; 

import sys


def maxSubArraySum(a, size):
    max_so_far = -(sys .maxsize - 1)
    max_ending_here = 0
    for i in range(size):
        max_ending_here = max_ending_here + a[i]
        if (max_so_far < max_ending_here):
            max_so_far = max_ending_here
        if (max_ending_here < 0):
            max_ending_here = 0
    return max_so_far


def maxSum(a, n):
    S = 0
    S1 = maxSubArraySum(a, n)
    for i in range(n):
        S += a[i]
    return (2 * S1 - S)


if __name__ == "__main__":
    a = [-35, 32, -24, 0, 27, -10, 0, -19]
    n = len(a)
    print(maxSum(a, n))

# Expected output:
99
# minimize the difference between minimum and maximum elements | function to minimize the difference between minimum and maximum elements ; find max and min elements of the array ; check whether the difference between the max and min element is less than or equal to k or not ; calculate average of max and min ; if the array element is greater than the average then decrease it by k ; if the array element is smaller than the average then increase it by k ; find max and min of the modified array ; return the new difference ; 
def minimizeDiff(arr, n, k):
    max_element = max(arr)
    min_element = min(arr)
    if ((max_element - min_element) <= k):
        return (max_element - min_element)
    avg = (max_element + min_element) // 2
    for i in range(n):
        if (arr[i] > avg):
            arr[i] -= k
        else:
            arr[i] += k
    max_element = max(arr)
    min_element = min(arr)
    return (max_element - min_element)


if __name__ == "__main__":
    arr = [3, 16, 12, 9, 20]
    n = 5
    k = 3
    print("Max height difference =", minimizeDiff(arr, n, k))

# Expected output:
Max height difference = 11
# maximum litres of water that can be bought with n rupees | python3 implementation of the above approach ; if buying glass bottles is profitable ; glass bottles that can be bought ; change budget according the bought bottles ; plastic bottles that can be bought ; if only plastic bottles need to be bought ; 
def maxLitres(budget, plastic, glass, refund):
    if glass - refund < plastic:
        ans = max((budget - refund) // (glass - refund), 0)
        budget -= ans * (glass - refund)
        ans += budget // plastic
        print(ans)
    else:
        print(budget // plastic)


budget, plastic, glass, refund = 10, 11, 9, 8
maxLitres(budget, plastic, glass, refund)

# Expected output:
2
# find number from given list for which value of the function is closest to a | function to find number from given list for which value of the function is closest to a ; stores the final index ; declaring a variable to store the minimum absolute difference ; finding f ( n ) ; updating the index of the answer if new absolute difference is less than tmp ; 
def leastValue(P, A, N, a):
    ans = -1
    tmp = float('inf')
    for i in range(N):
        t = P - a[i] * 0.006
        if abs(t - A) < tmp:
            tmp = abs(t - A)
            ans = i
    return a[ans]


N, P, A = 2, 12, 5
a = [1000, 2000]
print(leastValue(P, A, N, a))

# Expected output:
1000
# find permutation of n which is divisible by 3 but not divisible by 6 | python3 program to find permutation of n which is divisible by 3 but not divisible by 6 ; function to find the permutation ; length of integer ; if integer is even ; return odd integer ; rotate integer ; return - 1 in case no required permutation exists ; 

from math import log10, ceil, pow


def findPermutation(n):
    len = ceil(log10(n))
    for i in range(0, len, 1):
        if n % 2 != 0:
            return n
        else:
            n = ((n / 10) + (n % 10) * pow(10, len - i - 1))
            continue
    return -1


if __name__ == '__main__':
    n = 132
    print(int(findPermutation(n)))

# Expected output:
213
# maximum score after flipping a binary matrix atmost k times | python3 program to find the maximum score after flipping a binary matrix atmost k times ; function to find maximum score of matrix ; find value of rows having first column value equal to zero ; update those rows which lead to maximum score after toggle ; calculating answer ; check if k > 0 we can toggle if necessary . ; return max answer possible ; 

n = 3
m = 4


def maxMatrixScore(A, K):
    update = {}
    for i in range(0, n):
        if A[i][0] == 0:
            ans = 0
            for j in range(1, m):
                ans = ans + A[i][j] * 2 ** (m - j - 1)
            update[ans] = i
    for idx in update .values():
        for j in range(0, m):
            A[idx][j] = (A[idx][j] + 1) % 2
        K -= 1
        if K <= 0:
            break
    ans = 0
    for j in range(0, m):
        zero, one = 0, 0
        for i in range(0, n):
            if A[i][j] == 0:
                zero += 1
            else:
                one += 1
        if K > 0 and zero > one:
            ans += zero * 2 ** (m - j - 1)
            K -= 1
        else:
            ans += one * 2 ** (m - j - 1)
    return ans


if __name__ == "__main__":
    A = [[0, 0, 1, 1], [1, 0, 1, 0], [1, 1, 0, 0]]
    K = 2
    print(maxMatrixScore(A, K))

# Expected output:
36
# check if it is possible to serve customer queue with different notes | function that returns true is selling of the tickets is possible ; nothing to return to the customer ; check if 25 can be returned to customer . ; try returning one 50 and one 25 ; try returning three 25 ; if the loop did not break , all the tickets were sold ; 
def isSellingPossible(n, a):
    c25 = 0
    c50 = 0
    i = 0
    while (i < n):
        if (a[i] == 25):
            c25 += 1
        elif (a[i] == 50):
            c50 += 1
            if (c25 == 0):
                break
            c25 -= 1
        else:
            if (c50 > 0 and c25 > 0):
                c50 -= 1
                c25 -= 1
            elif (c25 >= 3):
                c25 -= 3
            else:
                break
        i += 1
    if (i == n):
        return True
    else:
        return False


a = [25, 25, 50, 100]
n = len(a)
if (isSellingPossible(n, a)):
    print("YES")
else:
    print("NO")

# Expected output:
YES
# check if a cell can be visited more than once in a string | function to check if any cell can be visited more than once ; array to mark cells ; traverse the string ; increase the visit count of the left and right cells within the array which can be visited ; if any cell can be visited more than once , return true ; 
def checkIfOverlap(str):
    length = len(str)
    visited = [0] * (length + 1)
    for i in range(length):
        if str[i] == ".":
            continue
        for j in range(
                max(0, i - ord(str[i]), min(length, i + ord(str[i])) + 1)):
            visited[j] += 1
    for i in range(length):
        if visited[i] > 1:
            return True
    return False


if __name__ == "__main__":
    str = ".2..2."
    if checkIfOverlap(str):
        print("YES")
    else:
        print("NO")

# Expected output:
YES
# check if a number has digits in the given order | check if the digits follow the correct order ; to store the previous digit ; pointer to tell what type of sequence are we dealing with ; check if we have same digit as the previous digit ; checking the peak point of the number ; check if we have same digit as the previous digit ; check if the digit is greater than the previous one if true , then break from the loop as we are in descending order part ; 
def isCorrectOrder(n):
    flag = True
    prev = -1
    type = -1
    while (n != 0):
        if (type == -1):
            if (prev == -1):
                prev = n % 10
                n = int(n / 10)
                continue
            if (prev == n % 10):
                flag = False
                break
            if (prev > n % 10):
                type = 1
                prev = n % 10
                n = int(n / 10)
                continue
            prev = n % 10
            n = int(n / 10)
        else:
            if (prev == n % 10):
                flag = False
                break
            if (prev < n % 10):
                flag = False
                break
            prev = n % 10
            n = int(n / 10)
    return flag


n = 123454321
if (isCorrectOrder(n)):
    print("YES")
else:
    print("NO")

# Expected output:
YES
# coin game of two corners ( greedy approach ) | returns optimal value possible that a player can collect from an array of coins of size n . note than n must be even ; find sum of odd positioned coins ; find sum of even positioned coins ; print even or odd coins depending upon which sum is greater . ; 
def printCoins(arr, n):
    oddSum = 0
    for i in range(0, n, 2):
        oddSum += arr[i]
    evenSum = 0
    for i in range(1, n, 2):
        evenSum += arr[i]
    if oddSum > evenSum:
        start = 0
    else:
        start = 1
    for i in range(start, n, 2):
        print(arr[i], end=" ")


if __name__ == "__main__":
    arr1 = [8, 15, 3, 7]
    n = len(arr1)
    printCoins(arr1, n)
    print()
    arr2 = [2, 2, 2, 2]
    n = len(arr2)
    printCoins(arr2, n)
    print()
    arr3 = [20, 30, 2, 2, 2, 10]
    n = len(arr3)
    printCoins(arr3, n)

# Expected output:
15 7 
2 2 
30 2 10
# prim 's algorithm (simple implementation for adjacency matrix representation) | python3 implementation to find minimum spanning tree for adjacency representation . ; returns true if edge u - v is a valid edge to be include in mst . an edge is valid if one end is already included in mst and other is not in mst . ; include first vertex in mst ; keep adding edges while number of included edges does not become v - 1. ; find minimum weight valid edge . ; 

from sys import maxsize
INT_MAX = maxsize
V = 5


def isValidEdge(u, v, inMST):
    if u == v:
        return False
    if inMST[u] == False and inMST[v] == False:
        return False
    elif inMST[u] and inMST[v]:
        return False
    return True


def primMST(cost):
    inMST = [False] * V
    inMST[0] = True
    edge_count = 0
    mincost = 0
    while edge_count < V - 1:
        minn = INT_MAX
        a = -1
        b = -1
        for i in range(V):
            for j in range(V):
                if cost[i][j] < minn:
                    if isValidEdge(i, j, inMST):
                        minn = cost[i][j]
                        a = i
                        b = j
        if a != -1 and b != -1:
            print("Edge %d: (%d, %d) cost: %d" % (edge_count, a, b, minn))
            edge_count += 1
            mincost += minn
            inMST[b] = inMST[a] = True
    print("Minimum cost = %d" % mincost)


if __name__ == "__main__":
    cost = [
        [
            INT_MAX, 2, INT_MAX, 6, INT_MAX], [
            2, INT_MAX, 3, 8, 5], [
                INT_MAX, 3, INT_MAX, INT_MAX, 7], [
                    6, 8, INT_MAX, INT_MAX, 9], [
                        INT_MAX, 5, 7, 9, INT_MAX]]
    primMST(cost)

# Expected output:
Edge 0: (0, 1) cost: 2
Edge 1: (1, 2) cost: 3
Edge 2: (1, 4) cost: 5
Edge 3: (0, 3) cost: 6
Minimum cost = 16
# subarray whose absolute sum is closest to k | function to return the index ; add last element tp currsum ; save difference of previous iteration ; calculate new difference ; when the sum exceeds k ; current difference greater in magnitude store temporary result ; difference in previous was lesser in previous , right index = j - 1 ; in next iteration , left index increases but right index remains the same update currsum and i accordingly ; case to simply increase right index ; check if lesser deviation found ; 
def getSubArray(arr, n, K):
    currSum = 0
    prevDif = 0
    currDif = 0
    result = [-1, -1, abs(K - abs(currSum))]
    resultTmp = result
    i = 0
    j = 0
    while (i <= j and j < n):
        currSum += arr[j]
        prevDif = currDif
        currDif = K - abs(currSum)
        if (currDif <= 0):
            if abs(currDif) < abs(prevDif):
                resultTmp = [i, j, currDif]
            else:
                resultTmp = [i, j - 1, prevDif]
            currSum -= (arr[i] + arr[j])
            i += 1
        else:
            resultTmp = [i, j, currDif]
            j += 1
        if (abs(resultTmp[2]) < abs(result[2])):
            result = resultTmp
    return result


def main():
    arr = [15, -3, 5, 2, 7, 6, 34, -6]
    n = len(arr)
    K = 50
    [i, j, minDev] = getSubArray(arr, n, K)
    if (i == -1):
        print("The empty array shows minimum Deviation")
        return 0
    for i in range(i, j + 1):
        print(arr[i],)


main()

# Expected output:
-3
5
2
7
6
34
# length and breadth of rectangle such that ratio of area to diagonal ^ 2 is maximum | function to print length and breadth ; sort the input array ; create array vector of integers occurring in pairs ; push the same pairs ; calculate length and breadth as per requirement ; check for given condition ; print the required answer ; 
def findLandB(arr, n):
    arr .sort(reverse=False)
    arr_pairs = []
    for i in range(n - 1):
        if (arr[i] == arr[i + 1]):
            arr_pairs .append(arr[i])
            i += 1
    length = arr_pairs[0]
    breadth = arr_pairs[1]
    size = len(arr_pairs)
    for i in range(1, size - 1):
        if ((int(length / breadth) + int(breadth / length)) >
                (int(arr_pairs[i] / arr_pairs[i - 1]) + int(arr_pairs[i - 1] / arr_pairs[i]))):
            length = arr_pairs[i]
            breadth = arr_pairs[i - 1]
    print(length, ",", breadth)


if __name__ == '__main__':
    arr = [4, 2, 2, 2, 5, 6, 5, 6, 7, 2]
    n = len(arr)
    findLandB(arr, n)

# Expected output:
2 , 2
# smallest sum contiguous subarray | set | function to find the smallest sum contiguous subarray ; first invert the sign of the elements ; apply the normal kadane algorithm but on the elements of the array having inverted sign ; invert the answer to get minimum val ; 
def smallestSumSubarr(arr, n):
    for i in range(n):
        arr[i] = -arr[i]
    sum_here = arr[0]
    max_sum = arr[0]
    for i in range(1, n):
        sum_here = max(sum_here + arr[i], arr[i])
        max_sum = max(max_sum, sum_here)
    return (-1) * max_sum


arr = [3, -4, 2, -3, -1, 7, -5]
n = len(arr)
print("Smallest sum:", smallestSumSubarr(arr, n))

# Expected output:
Smallest sum: -6
# maximum number by concatenating every element in a rotation of an array | function to print the largest number ; store the index of largest left most digit of elements ; iterate for all numbers ; check for the last digit ; check for the largest left most digit ; print the rotation of array ; print the rotation of array ; 
def printLargest(a, n):
    max = -1
    ind = -1
    for i in range(0, n):
        num = a[i]
        while (num):
            r = num % 10
            num = num / 10
            if (num == 0):
                if (max < r):
                    max = r
                    ind = i
    for i in range(ind, n):
        print(a[i], end=''),
    for i in range(0, ind):
        print(a[i], end='')


if __name__ == "__main__":
    a = [54, 546, 548, 60]
    n = len(a)
    printLargest(a, n)

# Expected output:
5454654860
# minimum operations to make gcd of array a multiple of k | python 3 program to make gcd of array a multiple of k . ; if array value is not 1 and it is greater than k then we can increase the or decrease the remainder obtained by dividing k from the ith value of array so that we get the number which is either closer to k or its multiple ; else we only have one choice which is to increment the value to make equal to k ; 
def MinOperation(a, n, k):
    result = 0
    for i in range(n):
        if (a[i] != 1 and a[i] > k):
            result = (result + min(a[i] % k, k - a[i] % k))
        else:
            result = result + k - a[i]
    return result


if __name__ == "__main__":
    arr = [4, 5, 6]
    n = len(arr)
    k = 5
    print(MinOperation(arr, n, k))

# Expected output:
2
# maximum product subset of an array | python3 program to find maximum product of a subset . ; find count of negative numbers , count of zeros , negative number with least absolute value and product of non - zero numbers ; if number is 0 , we don 't  multiply it with product. ; count negatives and keep track of negative number with least absolute value . ; if there are all zeros ; if there are odd number of negative numbers ; exceptional case : there is only negative and all other are zeros ; otherwise result is product of all non - zeros divided by negative number with least absolute value ; 
def maxProductSubset(a, n):
    if n == 1:
        return a[0]
    max_neg = -999999999999
    count_neg = 0
    count_zero = 0
    prod = 1
    for i in range(n):
        if a[i] == 0:
            count_zero += 1
            continue
        if a[i] < 0:
            count_neg += 1
            max_neg = max(max_neg, a[i])
        prod = prod * a[i]
    if count_zero == n:
        return 0
    if count_neg & 1:
        if (count_neg == 1 and count_zero > 0 and count_zero + count_neg == n):
            return 0
        prod = int(prod / max_neg)
    return prod


if __name__ == '__main__':
    a = [-1, -1, -2, 4, 3]
    n = len(a)
    print(maxProductSubset(a, n))

# Expected output:
24
# minimum fibonacci terms with sum equal to k | function to calculate fibonacci terms ; calculate all fibonacci terms which are less than or equal to k . ; if next term is greater than k do not push it in vector and return . ; function to find the minimum number of fibonacci terms having sum equal to k . ; vector to store fibonacci terms . ; subtract fibonacci terms from sum k until sum > 0. ; divide sum k by j - th fibonacci term to find how many terms it contribute in sum . ; 
def calcFiboTerms(fiboTerms, K):
    i = 3
    fiboTerms .append(0)
    fiboTerms .append(1)
    fiboTerms .append(1)
    while True:
        nextTerm = (fiboTerms[i - 1] + fiboTerms[i - 2])
        if nextTerm > K:
            return
        fiboTerms .append(nextTerm)
        i += 1


def findMinTerms(K):
    fiboTerms = []
    calcFiboTerms(fiboTerms, K)
    count, j = 0, len(fiboTerms) - 1
    while K > 0:
        count += K // fiboTerms[j]
        K %= fiboTerms[j]
        j -= 1
    return count


if __name__ == "__main__":
    K = 17
    print(findMinTerms(K))

# Expected output:
3
# smallest number with sum of digits as n and divisible by 10 ^ n | python program to find smallest number to find smallest number with n as sum of digits and divisible by 10 ^ n . ; if n = 0 the string will be 0 ; if n is not perfectly divisible by 9 output the remainder ; print 9 n / 9 times ; append n zero 's to the number so  as to make it divisible by 10^n ; 

import math


def digitsNum(N):
    if (N == 0):
        print("0", end="")
    if (N % 9 != 0):
        print(N % 9, end="")
    for i in range(1, int(N / 9) + 1):
        print("9", end="")
    for i in range(1, N + 1):
        print("0", end="")
    print()


N = 5
print("The number is : ", end="")
digitsNum(N)

# Expected output:
The number is : 500000
# divide 1 to n into two groups with minimum sum difference | python program to divide n integers in two groups such that absolute difference of their sum is minimum ; to print vector along size ; print vector size ; print vector elements ; to divide n in two groups such that absolute difference of their sum is minimum ; find sum of all elements upto n ; sum of elements of group1 ; if sum is greater then or equal to 0 include i in group 1 otherwise include in group2 ; decrease sum of group1 ; print both the groups ; 

import math


def printVector(v):
    print(len(v))
    for i in range(0, len(v)):
        print(v[i], end=" ")
    print()


def findTwoGroup(n):
    sum = n * (n + 1) / 2
    group1Sum = sum / 2
    group1 = []
    group2 = []
    for i in range(n, 0, -1):
        if (group1Sum - i >= 0):
            group1 .append(i)
            group1Sum -= i
        else:
            group2 .append(i)
    printVector(group1)
    printVector(group2)


n = 5
findTwoGroup(n)

# Expected output:
2
5 2 
3
4 3 1
# maximum number of customers that can be satisfied with given quantity | python3 program to find maximum number of customers that can be satisfied ; print maximum number of satisfied customers and their indexes ; creating an vector of pair of total demand and customer number ; sorting the customers according to their total demand ; taking the first k customers that can be satisfied by total amount d ; 

v = []


def solve(n, d, a, b, arr):
    first, second = 0, 1
    for i in range(n):
        m = arr[i][0]
        t = arr[i][1]
        v .append([a * m + b * t, i + 1])
    v .sort()
    ans = []
    for i in range(n):
        if v[i][first] <= d:
            ans .append(v[i][second])
            d -= v[i][first]
    print(len(ans))
    for i in range(len(ans)):
        print(ans[i], end=" ")


if __name__ == '__main__':
    n = 5
    d = 5
    a = 1
    b = 1
    arr = [[2, 0], [3, 2], [4, 4], [10, 0], [0, 1]]
    solve(n, d, a, b, arr)

# Expected output:
2
5 1
# partition into two subarrays of lengths k and ( n | function to calculate max_difference ; sum of the array ; sort the array in descending order ; calculating max_difference ; 
def maxDifference(arr, N, k):
    S = 0
    S1 = 0
    max_difference = 0
    for i in range(N):
        S += arr[i]
    arr .sort(reverse=True)
    M = max(k, N - k)
    for i in range(M):
        S1 += arr[i]
    max_difference = S1 - (S - S1)
    return max_difference


arr = [8, 4, 5, 2, 10]
N = len(arr)
k = 2
print(maxDifference(arr, N, k))

# Expected output:
17