giulio98/xlcost-single-prompt huggingface dataset:
# find minimum value of the expression by choosing k elements from given array | function to find the minimum possible of the expression by choosing exactly k ( ? n ) integers form given array arr ; sorting the array for least k element selection ; select first k elements from sorted array ; return value of solved expression ; 
def minimumValue(arr, n, k):
    arr .sort()
    answer = 0
    for i in range(k):
        answer += arr[i] * arr[i]
    return answer * (2 * k - 2)


if __name__ == '__main__':
    arr = [4, 21, 5, 3, 8]
    k = 3
    n = len(arr)
    print(minimumValue(arr, n, k))

# Expected output:
200
# transform n to minimum possible value | python3 program to transform n to the minimum value ; initialising the answer ; function to find the digitsum ; iterate over all digits and add them ; return the digit su , ; function to transform n to the minimum value ; if the final value is lesser than least value ; if final value is equal to least value then check for lesser number of steps to reach this value ; the value will be obtained in less than 15 steps as proved so applying normal recursive operations ; 

import sys
min_val = sys .maxsize
min_steps = 0


def sumOfDigits(n):
    s = str(n)
    sum = 0
    for i in range(len(s)):
        sum += (ord(s[i]) - ord('0'))
    return sum


def Transform(n, d, steps):
    global min_val
    global min_steps
    if (n < min_val):
        min_val = n
        min_steps = steps
    elif (n == min_val):
        min_steps = min(min_steps, steps)
    if (steps < 15):
        Transform(sumOfDigits(n), d, steps + 1)
        Transform(n + d, d, steps + 1)


if __name__ == "__main__":
    N = 9
    D = 3
    Transform(N, D, 0)
    print(min_val, min_steps)

# Expected output:
3 2
# remove all 1 s from the adjacent left of 0 s in a binary array | function to find the maximum number of 1 's before 0 ; traverse the array ; if value is 1 ; if consecutive 1 followed by 0 , then update the maxcnt ; print the maximum consecutive 1 's  followed by 0 ; 
def noOfMoves(arr, n):
    cnt = 0
    maxCnt = 0
    for i in range(n):
        if (arr[i] == 1):
            cnt += 1
        else:
            if (cnt != 0):
                maxCnt = max(maxCnt, cnt)
                cnt = 0
    print(maxCnt)


if __name__ == '__main__':
    arr = [0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1]
    N = len(arr)
    noOfMoves(arr, N)
    arr1 = [1, 0, 1, 0, 1, 0, 1, 0]
    N = len(arr1)
    noOfMoves(arr1, N)

# Expected output:
4
1
# check if given coins can be used to pay a value of s | function to check if it is possible to pay a value ; loop to add the value of coin a ; condition to check if it is possible to pay a value of s ; 
def knowPair(a, b, n, s, m):
    i = 0
    rem = 0
    count_b = 0
    flag = 0
    while (i <= a):
        rem = s - (n * i)
        count_b = rem // m
        if (rem % m == 0 and count_b <= b):
            flag = 1
        i += 1
    if (flag == 1):
        print("YES")
    else:
        print("NO")


if __name__ == '__main__':
    A = 1
    B = 2
    n = 3
    S = 4
    m = 2
    knowPair(A, B, n, S, m)

# Expected output:
YES
# sum of all numbers in the given range which are divisible by m | function to find the sum of numbers divisible by m in the given range ; variable to store the sum ; running a loop from a to b and check if a number is divisible by i . ; if the number is divisible , then add it to sum ; return the sum ; 
def sumDivisibles(A, B, M):
    sum = 0
    for i in range(A, B + 1):
        if (i % M == 0):
            sum += i
    return sum


if __name__ == "__main__":
    A = 6
    B = 15
    M = 3
    print(sumDivisibles(A, B, M))

# Expected output:
42
# sum of all numbers in the given range which are divisible by m | function to find the largest number smaller than or equal to n that is divisible by k ; finding the remainder when n is divided by k ; if the remainder is 0 , then the number itself is divisible by k ; else , then the difference between n and remainder is the largest number which is divisible by k ; function to find the smallest number greater than or equal to n that is divisible by k ; finding the remainder when n is divided by k ; if the remainder is 0 , then the number itself is divisible by k ; else , then the difference between n and remainder is the largest number which is divisible by k ; function to find the sum of numbers divisible by m in the given range ; variable to store the sum ; to bring the smallest and largest numbers in the range [ a , b ] ; to count the number of terms in the ap ; sum of n terms of an ap ; 
def findSmallNum(N, K):
    rem = N % K
    if (rem == 0):
        return N
    else:
        return N - rem


def findLargeNum(N, K):
    rem = (N + K) % K
    if (rem == 0):
        return N
    else:
        return N + K - rem


def sumDivisibles(A, B, M):
    sum = 0
    first = findSmallNum(A, M)
    last = findLargeNum(B, M)
    if (first < A):
        first += M
    if (last > B):
        first -= M
    n = (B // M) - (A - 1) // M
    return n * (first + last) // 2


if __name__ == '__main__':
    A = 6
    B = 15
    M = 3
    print(sumDivisibles(A, B, M))

# Expected output:
42
# count of all unique substrings with non | function to count all unique distinct character substrings ; hashmap to store all substrings ; iterate over all the substrings ; boolean array to maintain all characters encountered so far ; variable to maintain the subtill current position ; get the position of the character in the string ; check if the character is encountred ; add the current character to the substring ; insert subin hashmap ; 
def distinctSubstring(P, N):
    S = dict()
    for i in range(N):
        freq = [False] * 26
        s = ""
        for j in range(i, N):
            pos = ord(P[j]) - ord('a')
            if (freq[pos]):
                break
            freq[pos] = True
            s += P[j]
            S[s] = 1
    return len(S)


S = "abba"
N = len(S)
print(distinctSubstring(S, N))

# Expected output:
4
# sum of all subarrays of size k | function to find the sum of all subarrays of size k ; loop to consider every subarray of size k ; initialize sum = 0 ; calculate sum of all elements of current subarray ; prsum of each subarray ; 
def calcSum(arr, n, k):
    for i in range(n - k + 1):
        sum = 0
        for j in range(i, k + i):
            sum += arr[j]
        print(sum, end=" ")


arr = [1, 2, 3, 4, 5, 6]
n = len(arr)
k = 3
calcSum(arr, n, k)

# Expected output:
6 9 12 15
# sum of all subarrays of size k | function to find the sum of all subarrays of size k ; initialize sum = 0 ; consider first subarray of size k store the sum of elements ; print the current sum ; consider every subarray of size k remove first element and add current element to the window ; add the element which enters into the window and subtract the element which pops out from the window of the size k ; print the sum of subarray ; 
def calcSum(arr, n, k):
    sum = 0
    for i in range(k):
        sum += arr[i]
    print(sum, end=" ")
    for i in range(k, n):
        sum = (sum - arr[i - k]) + arr[i]
        print(sum, end=" ")


if __name__ == "__main__":
    arr = [1, 2, 3, 4, 5, 6]
    n = len(arr)
    k = 3
    calcSum(arr, n, k)

# Expected output:
6 9 12 15
# number of indices pair such that element pair sum from first array is greater than second array | python 3 program to find the number of indices pair such that pair sum from first array is greater than second array ; function to get the number of pairs of indices { i , j } in the given two arrays a and b such that a [ i ] + a [ j ] > b [ i ] + b [ j ] ; intitializing the difference array d ; computing the difference between the elements at every index and storing it in the array d ; sort the array d ; variable to store the total number of pairs that satisfy the given condition ; loop to iterate through the difference array d and find the total number of pairs of indices that follow the given condition ; if the value at the index i is positive , then it remains positive for any pairs with j such that j > i . ; if the value at that index is negative then we need to find the index of the value just greater than - d [ i ] ; 

import bisect


def getPairs(A, B, n):
    D = [0] * (n)
    for i in range(n):
        D[i] = A[i] - B[i]
    D .sort()
    total = 0
    for i in range(n - 1, -1, -1):
        if (D[i] > 0):
            total += n - i - 1
        else:
            k = bisect .bisect_right(D, -D[i], 0, len(D))
            total += n - k
    return total


if __name__ == "__main__":
    n = 5
    A = []
    B = []
    A .append(4)
    A .append(8)
    A .append(2)
    A .append(6)
    A .append(2)
    B .append(4)
    B .append(5)
    B .append(4)
    B .append(1)
    B .append(3)
    print(getPairs(A, B, n))

# Expected output:
7
# number of pairs such that their hcf and lcm is equal | function to return hcf of two numbers ; function to return lcm of two numbers ; returns the number of valid pairs ; traversing the array . for each array element , checking if it follow the condition ; 
def gcd(a, b):
    if (a == 0):
        return b
    return gcd(b % a, a)


def lcm(a, b):
    return (a * b) / gcd(a, b)


def countPairs(arr, n):
    ans = 0
    for i in range(n):
        for j in range(i+1, n):
            if (lcm(arr[i], arr[j]) == gcd(arr[i], arr[j])):
                ans += 1
    return ans


if __name__ == '__main__':
    arr = [1, 1, 1]
    n = len(arr)
    print(countPairs(arr, n))

# Expected output:
3
# number of pairs such that their hcf and lcm is equal | python 3 program to count number of pairs such that their hcf and lcm are equal ; function to count number of pairs such that their hcf and lcm are equal ; store frequencies of array elements ; count of pairs ( arr [ i ] , arr [ j ] ) where arr [ i ] = arr [ j ] ; count of pairs ( arr [ i ] , arr [ j ] ) where arr [ i ] = arr [ j ] , ; 

from collections import defaultdict


def countPairs(a, n):
    frequency = defaultdict(int)
    for i in range(n):
        frequency[a[i]] += 1
    count = 0
    for x in frequency .keys():
        f = frequency[x]
        count += f * (f - 1) // 2
    return count


if __name__ == "__main__":
    arr = [1, 1, 1]
    n = len(arr)
    print(countPairs(arr, n))

# Expected output:
3
# find the maximum possible value of last element of the array | function to find the maximum possible value of last element of the array ; traverse for all element ; find the distance ; if moves less than distance then we can not move this number to end ; how many number we can move to end ; take the minimum of both of them ; increment in the end ; remove taken moves ; return the last element ; 
def maxValue(arr, n, moves):
    for i in range(n - 2, -1, -1):
        if (arr[i] > 0):
            distance = n - 1 - i
            if (moves < distance):
                break
            can_take = moves // distance
            take = min(arr[i], can_take)
            arr[n - 1] += take
            moves -= take * distance
    return arr[n - 1]


if __name__ == '__main__':
    arr = [2, 3, 0, 1]
    M = 5
    N = len(arr)
    print(maxValue(arr, N, M))

# Expected output:
3
# minimum number of factorials whose sum is equal to n | array to calculate all factorials less than or equal to n since there can be only 14 factorials till 10 ^ 10 hence the maximum size of fact [ ] is 14 ; store the actual size of fact [ ] ; function to precompute factorials till n ; precomputing factorials ; function to find the minimum number of factorials whose sum represents n ; precompute factorials ; initialize result ; traverse through all factorials ; find factorials ; prmin count ; prresult ; 

fact = [0] * 14
size = 1


def preCompute(N):
    global size
    fact[0] = 1
    i = 1
    while fact[i - 1] <= N:
        fact[i] = fact[i - 1] * i
        size += 1
        i += 1


def findMin(N):
    preCompute(N)
    originalN = N
    ans = []
    for i in range(size - 1, -1, -1):
        while (N >= fact[i]):
            N -= fact[i]
            ans .append(fact[i])
    print(len(ans))
    for i in ans:
        print(i, end=" ")


n = 27
findMin(n)

# Expected output:
3
24 2 1
# longest increasing sub | function to find the lcs ; loop to create frequency array ; 
def findLCS(arr, n):
    mp = {}
    for i in range(n):
        if arr[i] in mp:
            mp[arr[i]] += 1
        else:
            mp[arr[i]] = 1
    return len(mp)


n = 3
arr = [3, 2, 1]
print(findLCS(arr, n))

# Expected output:
3
# path with maximum product in 2 | python program to find maximum product path from ( 0 , 0 ) to ( n - 1 , m - 1 ) ; function to find maximum product ; it will store the maximum product till a given cell . ; it will store the minimum product till a given cell ( for - ve elements ) ; if we are at topmost or leftmost , just copy the elements . ; if we 're not at the  above, we can consider  the above value. ; if we 're not on the  leftmost, we can consider  the left value. ; store max & min product till i , j . ; return the max product path from 0 , 0. n - 1 , m - 1. ; 

import sys
N = 3
M = 3


def maxProductPath(arr):
    maxPath = [[0 for i in range(M)]for j in range(N)]
    minPath = [[0 for i in range(M)]for j in range(N)]
    for i in range(N):
        for j in range(M):
            minVal = sys .maxsize
            maxVal = -sys .maxsize
            if (i == 0 and j == 0):
                maxVal = arr[i][j]
                minVal = arr[i][j]
            if (i > 0):
                tempMax = max(maxPath[i - 1][j] * arr[i]
                              [j], minPath[i - 1][j] * arr[i][j])
                maxVal = max(maxVal, tempMax)
                tempMin = min(maxPath[i - 1][j] * arr[i]
                              [j], minPath[i - 1][j] * arr[i][j])
                minVal = min(minVal, tempMin)
            if (j > 0):
                tempMax = max(maxPath[i][j - 1] * arr[i]
                              [j], minPath[i][j - 1] * arr[i][j])
                maxVal = max(maxVal, tempMax)
                tempMin = min(maxPath[i][j - 1] * arr[i]
                              [j], minPath[i][j - 1] * arr[i][j])
                minVal = min(minVal, tempMin)
            maxPath[i][j] = maxVal
            minPath[i][j] = minVal
    return maxPath[N - 1][M - 1]


if __name__ == '__main__':
    arr = [[1, -2, 3], [4, -5, 6], [-7, -8, 9]]
    print(maxProductPath(arr))

# Expected output:
2016
# vertical and horizontal retrieval ( mrt ) on tapes | python3 program to print vertical filling ; 2d matrix for vertical insertion on tapes ; it is used for checking whether tape is full or not ; it is used for calculating total retrieval time ; it is used for calculating mean retrieval time ; it is used for calculating mean retrieval time ; vertical insertion on tape ; initialize variables to 0 for each iteration ; used for getting ' sum ' sizes of records in tape to determine whether tape is full or not ; if tape is not full ; check for ability of tapes to hold value ; initialize variables to 0 for each iteration ; display elements of tape ; calculating total retrieval time ; mrt formula ; calculating mean retrieval time using formula ; v . size ( ) is function of vector is used to get size of vector ; 

import numpy as np


def vertical_Fill(records, tape, m, n):
    v = np .zeros((m, n))
    sum = 0
    Retrieval_Time = 0
    Mrt = None
    z = 0
    j = 0
    for i in range(n):
        for j in range(m):
            sum = 0
            for k in range(i):
                sum += v[j][k]
            if (sum + records[z] <= tape[j]):
                v[j][i] = records[z]
                z += 1
        if (v[2][i] == 0):
            break
    for i in range(m):
        Retrieval_Time = 0
        print("tape", i + 1, ": [", end="")
        for j in range(n):
            if (v[i][j] != 0):
                print(v[i][j], end=" ")
            else:
                break

        print("]", end="")
        k = 0
        while v[i][k] != 0:
            Retrieval_Time += v[i][k] * (j - k)
            k += 1
        Mrt = Retrieval_Time / j
        print("MRT :", Mrt)


if __name__ == "__main__":
    records = [15, 2, 8, 23, 45, 50, 60, 120]
    tape = [25, 80, 160]
    n = len(records)
    m = len(tape)
    records .sort()
    vertical_Fill(records, tape, m, n)

# Expected output:
tape 1 : [2.0 23.0 ]MRT : 13.5
tape 2 : [8.0 45.0 ]MRT : 30.5
tape 3 : [15.0 50.0 60.0 ]MRT : 68.33333333333333
# minimum number of subsequences required to convert one string to another | python3 program to find the minimum number of subsequences required to convert one to another ; function to find the no of subsequences ; push the values of indexes of each character ; find the next index available in the array ; if character is not in a ; check if the next index is not equal to the size of array which means there is no index greater than minindex in the array ; update value of minindex with this index ; update the value of counter and minindex for next operation ; 

from bisect import bisect as upper_bound


def minSubsequnces(A, B):
    v = [[]for i in range(26)]
    minIndex = -1
    cnt = 1
    j = 0
    flag = 0
    for i in range(len(A)):
        p = ord(A[i]) - 97
        v[p].append(i)
    while (j < len(B)):
        p = ord(B[j]) - 97
        k = upper_bound(v[p], minIndex)
        if (len(v[p]) == 0):
            flag = 1
            break
        if (k != len(v[p])):
            minIndex = v[p][k]
            j = j + 1
        else:
            cnt = cnt + 1
            minIndex = -1
    if (flag == 1):
        return -1
    return cnt


A1 = "abbace"
B1 = "acebbaae"
print(minSubsequnces(A1, B1))

# Expected output:
3
# find two equal subsequences of maximum length with at least one different index | python implementation of the approach ; function to return the required length of the subsequences ; to store the result ; to store the last visited position of lowercase letters ; initialisation of frequency array to - 1 to indicate no character has previously occured ; for every character of the string ; get the index of the current character ; if the current character has appeared before in the string ; update the result ; update the last position of the current character ; 

MAX = 26


def maxLength(str, len):
    res = 0
    lastPos = [0] * MAX
    for i in range(MAX):
        lastPos[i] = -1
    for i in range(len):
        C = ord(str[i]) - ord('a')
        if (lastPos[C] != -1):
            res = max(len - (i - lastPos[C] - 1) - 1, res)
        lastPos[C] = i
    return res


if __name__ == '__main__':
    str = "geeksforgeeks"
    len = len(str)
    print(maxLength(str, len))

# Expected output:
12
# maximum profit by selling n items at two markets | python3 implementation of the approach ; max profit will be saved here ; loop to check all possible combinations of sales ; the sum of the profit after the sale for products 0 to i in market a ; the sum of the profit after the sale for products i to n in market b ; replace the value of max profit with a bigger value among maxp and suma + sumb ; return the value of max profit ; 
def maxProfit(a, b, n):
    maxP = -1
    for i in range(0, n + 1):
        sumA = sum(a[:i])
        sumB = sum(b[i:])
        maxP = max(maxP, sumA + sumB)
    return maxP


if __name__ == "__main__":
    a = [2, 3, 2]
    b = [10, 30, 40]
    print(maxProfit(a, b, 4))

# Expected output:
80
# partitions possible such that the minimum element divides all the other elements of the partition | python3 implementation of the approach ; function to return the count partitions possible from the given array such that the minimum element of any partition divides all the other elements of that partition ; initialize the count variable ; find the minimum element ; break if no minimum element present ; increment the count if minimum element present ; replace all the element divisible by min_elem ; 

import sys
INT_MAX = sys .maxsize


def countPartitions(A, N):
    count = 0
    for i in range(N):
        min_elem = min(A)
        if (min_elem == INT_MAX):
            break
        count += 1
        for i in range(N):
            if (A[i] % min_elem == 0):
                A[i] = INT_MAX
    return count


if __name__ == "__main__":
    arr = [7, 6, 5, 4, 3, 2, 2, 3]
    N = len(arr)
    print(countPartitions(arr, N))

# Expected output:
4
# minimum number of swaps to make two binary string equal | function to calculate min swaps to make binary strings equal ; count of zero 's  ; count of one 's  ; as discussed above ; 
def minSwaps(s1, s2):
    c0 = 0
    c1 = 0
    for i in range(len(s1)):
        if (s1[i] == '0' and s2[i] == '1'):
            c0 += 1
        elif (s1[i] == '1' and s2[i] == '0'):
            c1 += 1
    ans = c0 // 2 + c1 // 2
    if (c0 % 2 == 0 and c1 % 2 == 0):
        return ans
    elif ((c0 + c1) % 2 == 0):
        return ans + 2
    else:
        return -1


if __name__ == "__main__":
    s1 = "0011"
    s2 = "1111"
    ans = minSwaps(s1, s2)
    print(ans)

# Expected output:
1
# minimum changes required to make all element in an array equal | function to count of minimum changes required to make all elements equal ; store the count of each element as key - value pair in dictionary ; traverse through the dictionary and find the maximum occurring element ; return count of all element minus count of maximum occurring element ; 
def minChanges(arr, n):
    mp = dict()
    for i in range(n):
        if arr[i] in mp .keys():
            mp[arr[i]] += 1
        else:
            mp[arr[i]] = 1
    maxElem = 0
    for x in mp:
        maxElem = max(maxElem, mp[x])
    return n - maxElem


arr = [2, 3, 3, 4]
n = len(arr)
print(minChanges(arr, n))

# Expected output:
2
# minimum operations to make two numbers equal | python3 implementation of the above approach ; function to find the minimum no . of operations ; find the maximum of two and store it in p ; increase it until it is achievable from given n and m ; here value added to n and m will be s ( n ) = p - n + p - m ; check whether integer value of n exist by the formula n = ( - 1 + sqrt ( 1 + 8 * s ( n ) ) ) / 2 ; 

from math import sqrt, floor


def minOperations(n, m):
    a = 0
    k = 1
    p = max(n, m)
    while (n != m):
        s = float(p - n + p - m)
        q = (-1 + sqrt(8 * s + 1)) / 2
        if (q - floor(q) == 0):
            a = q
            n = m
        p = p + 1
    return a


if __name__ == "__main__":
    n = 1
    m = 3
    print(minOperations(n, m))

# Expected output:
3.0
# count of subarrays with sum at least k | function to return the number of subarrays with sum atleast k ; to store the right index and the current sum ; to store the number of sub - arrays ; for all left indexes ; get elements till current sum is less than k ; no such subarray is possible ; add all possible subarrays ; remove the left most element ; return the required answer ; 
def k_sum(a, n, k):
    r, sum = 0, 0
    ans = 0
    for l in range(n):
        while (sum < k):
            if (r == n):
                break
            else:
                sum += a[r]
                r += 1
        if (sum < k):
            break
        ans += n - r + 1
        sum -= a[l]
    return ans


a = [6, 1, 2, 7]
k = 10
n = len(a)
print(k_sum(a, n, k))

# Expected output:
2
# find if a crest is present in the index range [ l , r ] of the given array | function that returns true if the array contains a crest in the index range [ l , r ] ; to keep track of elements which satisfy the property ; property is satisfied for the current element ; cumulative sum ; if a crest is present in the given index range ; 
def hasCrest(arr, n, L, R):
    present = [0] * n
    for i in range(1, n - 2 + 1):
        if ((arr[i] <= arr[i + 1]) and (arr[i] <= arr[i - 1])):
            present[i] = 1
    for i in range(1, n):
        present[i] += present[i - 1]
    if (present[L] == present[R - 1]):
        return True
    return False


if __name__ == "__main__":
    arr = [2, 1, 3, 5, 12, 11, 7, 9]
    N = len(arr)
    L = 2
    R = 6
    if (hasCrest(arr, N, L, R)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes