giulio98/xlcost-single-prompt huggingface dataset:
# count of minimum numbers having k as the last digit required to obtain sum n | python3 program for the above approach ; stores the smallest number that ends with digit i ( 0 , 9 ) ; stores the minimum number of steps to create a number ending with digit i ; initialize elements as infinity ; minimum number ending with digit i ; minimum steps to create a number ending with digit i ; if n < smallestnumber then , return - 1 ; otherwise , return answer ; 

import sys


def minCount(N, K):
    SmallestNumber = [0 for i in range(10)]
    MinimumSteps = [0 for i in range(10)]
    for i in range(10):
        SmallestNumber[i] = sys .maxsize
        MinimumSteps[i] = sys .maxsize
    for i in range(1, 11, 1):
        num = K * i
        SmallestNumber[num % 10] = min(SmallestNumber[num % 10], num)
        MinimumSteps[num % 10] = min(MinimumSteps[num % 10], i)
    if (N < SmallestNumber[N % 10]):
        return -1
    else:
        return MinimumSteps[N % 10]


if __name__ == '__main__':
    N = 42
    K = 7
    print(minCount(N, K))

# Expected output:
6
# minimum number of operations required to make an array non | function to count the minimum number of steps required to make arr non - decreasing ; stores differences ; stores the max number ; traverse the array arr [ ] ; update mx ; update val ; stores the result ; iterate until 2 ^ res - 1 is less than val ; return the answer ; 
def countMinSteps(arr, N):
    val = 0
    mx = -10 ** 9
    for i in range(N):
        curr = arr[i]
        mx = max(mx, curr)
        val = max(val, mx - curr)
    res = 0
    while ((1 << res) - 1 < val):
        res += 1
    return res


if __name__ == '__main__':
    arr = [1, 7, 6, 5]
    N = len(arr)
    print(countMinSteps(arr, N))

# Expected output:
2
# minimum xor of at most k elements in range [ l , r ] | function for k = 2 ; function for k = 2 ; function for k = 2 ; function to calculate the minimum xor of at most k elements in [ l , r ] ; 
def func2(L, R, K):
    if (R - L >= 2):
        return 1
    return min(L, L ^ R)


def func3(L, R, K):
    if ((R ^ L) > L and (R ^ L) < R):
        return 0
    return func2(L, R, K)


def func4(L, R, K):
    if (R - L >= 4):
        return 0
    minval = L ^ (L + 1) ^ (L + 2) ^ (L + 3)
    return min(minval, func3(L, R, K))


def minimumXor(L, R, K):
    if (K > 4):
        return 0
    elif (K == 4):
        return func4(L, R, K)
    elif (K == 3):
        return func3(L, R, K)
    elif (K == 2):
        return func2(L, R, K)
    else:
        return L


if __name__ == '__main__':
    L, R, K = 1, 3, 3
    print(minimumXor(L, R, K))

# Expected output:
0
# nth term of ruler function series | function to count the number of set bits in the number n ; store the number of setbits ; update the value of n ; update the count ; return the total count ; function to find the nth term of the ruler function series ; store the result ; print the result ; 
def setBits(n):
    count = 0
    while (n > 0):
        n = n & (n - 1)
        count += 1
    return count


def findNthTerm(N):
    x = setBits(N ^ (N - 1))
    print(x)


N = 8
findNthTerm(N)

# Expected output:
4
# quadratic equation whose roots are reciprocal to the roots of given equation | function to find the quadratic equation having reciprocal roots ; print quadratic equation ; 
def findEquation(A, B, C):
    print("(" + str(C) + ")" + "x^2 +(" + str(B) + ")x + (" + str(A) + ") = 0")


if __name__ == "__main__":
    A = 1
    B = -5
    C = 6
    findEquation(A, B, C)

# Expected output:
(6)x^2 +(-5)x + (1) = 0
# minimize subtraction followed by increments of adjacent elements required to make all array elements equal | function to find the minimum number of moves required to make all array elements equal ; store the total sum of the array ; calculate total sum of the array ; if the sum is not divisible by n , then print " - 1" ; stores the average ; stores the count of operations ; traverse the array arr [ ] ; update number of moves required to make current element equal to avg ; update the overall count ; return the minimum operations required ; 
def findMinMoves(arr, N):
    sum = 0
    for i in range(N):
        sum += arr[i]
    if (sum % N != 0):
        return -1
    avg = sum // N
    total = 0
    needCount = 0
    for i in range(N):
        needCount += (arr[i] - avg)
        total = max(max(abs(needCount), arr[i] - avg), total)
    return total


if __name__ == '__main__':
    arr = [1, 0, 5]
    N = len(arr)
    print(findMinMoves(arr, N))

# Expected output:
3
# maximum amount of money that can be collected by a player in a game of coins | function to calculate the maximum amount collected by a ; stores the money obtained by a ; stores mid elements of odd sized rows ; size of current row ; increase money collected by a ; add coins at even indices to the amount collected by a ; print the amount ; 
def find(N, Arr):
    amount = 0
    mid_odd = []
    for i in range(N):
        siz = len(Arr[i])
        for j in range(0, siz // 2):
            amount = amount + Arr[i][j]
        if (siz % 2 == 1):
            mid_odd .append(Arr[i][siz // 2])
    mid_odd .sort(reverse=True)
    for i in range(len(mid_odd)):
        if i % 2 == 0:
            amount = amount + mid_odd[i]
    print(amount)


N = 2
Arr = [[5, 2, 3, 4], [1, 6]]
find(N, Arr)

# Expected output:
8
# check if an array can be split into k consecutive non | function to check if array can be split into k consecutive and non - overlapping subarrays of length m consisting of a single distinct element ; traverse over the range [ 0 , n - m - 1 ] ; check if arr [ i ] is the same as arr [ i + m ] ; increment current length t of pattern matched by 1 ; check if t is equal to m , increment count of total repeated pattern ; return true if length of total repeated pattern is k ; update length of the current pattern ; update count to 1 ; finally return false if no pattern found ; 
def checkPattern(arr, m, k, n):
    count = 1
    t = 0
    for i in range(n - m):
        if (arr[i] == arr[i + m]):
            t += 1
            if (t == m):
                t = 0
                count += 1
                if (count == k):
                    return "Yes"
        else:
            t = 0
            count = 1
    return "No"


if __name__ == '__main__':
    arr = [6, 1, 3, 3, 3, 3]
    M = 1
    K = 3
    N = len(arr)
    print(checkPattern(arr, M, K, N))

# Expected output:
Yes
# remove all occurrences of a word from a given string using z | function to fill the z - array for str ; l stores start index of window which matches with prefix of str ; r stores end index of window which matches with prefix of str ; iterate over the characters of str ; if i is greater thn r ; update l and r ; if substring match with prefix ; update r ; update z [ i ] ; update r ; update k ; if z [ k ] is less than remaining interval ; update z [ i ] ; start from r and check manually ; update r ; update z [ i ] ; update r ; function to remove all the occurrences of word from str ; create concatenated string " p $ t " ; store z array of concat ; stores string , str by removing all the occurrences of word from str ; stores length of word ; traverse the array , z [ ] ; if z [ i + psize + 1 ] equal to length of word ; update i ; 
def getZarr(st, Z):
    n = len(st)
    k = 0
    L = 0
    R = 0
    for i in range(1, n):
        if (i > R):
            L = R = i
            while (R < n and st[R - L] == st[R]):
                R += 1
            Z[i] = R - L
            R -= 1
        else:
            k = i - L
            if (Z[k] < R - i + 1):
                Z[i] = Z[k]
            else:
                L = i
                while (R < n and st[R - L] == st[R]):
                    R += 1
                Z[i] = R - L
                R -= 1


def goodStr(st, word):
    concat = word + "$" + st
    l = len(concat)
    Z = [0] * l
    getZarr(concat, Z)
    res = ""
    pSize = len(word)
    for i in range(l):
        if (i + pSize < l - 1 and Z[i + pSize + 1] == pSize):
            i += pSize - 1
        elif (i < len(st)):
            res += st[i]
    return res


if __name__ == "__main__":
    st = "Z-kmalgorithmkmiskmkmkmhelpfulkminkmsearching"
    word = "km"
    print(goodStr(st, word))

# Expected output:
Z-malgorithmmismmmhelpfulminmsearching
# count of substrings of a string containing another given string as a substring | set 2 | function to count the substrings of containing another given as a sub ; store length of s ; store length of t ; store the required count of substrings ; store the starting index of last occurence of t in s ; iterate in range [ 0 , n1 - n2 ] ; check if subfrom i to i + n2 is equal to t ; check if subfrom i to i + n2 is equal to t ; mark chk as false and break the loop ; if chk is true ; add ( i + 1 - last ) * ( n1 - ( i + n2 - 1 ) ) to answer ; update the last to i + 1 ; prthe answer ; 
def findOccurrences(S, T):
    n1 = len(S)
    n2 = len(T)
    ans = 0
    last = 0
    for i in range(n1 - n2 + 1):
        chk = True
        for j in range(n2):
            if (T[j] != S[i + j]):
                chk = False
                break
        if (chk):
            ans += (i + 1 - last) * (n1 - (i + n2 - 1))
            last = i + 1
    print(ans)


if __name__ == '__main__':
    S, T = "dabc", "ab"
    findOccurrences(S, T)

# Expected output:
4
# lexicographically largest n | function to find the lexicographically largest bitonic sequence of size n elements lies in the range [ low , high ] ; store index of highest element ; if high_index > ( n - 1 ) / 2 , then remaining n / 2 elements cannot be placed in bitonic order ; if high_index <= 0 , then set high_index as 1 ; stores the resultant sequence ; store the high value ; maintain strictly decreasing sequence from index high_index to 0 starting with temp ; store the value and decrement the temp variable by 1 ; maintain the strictly decreasing sequence from index high_index + 1 to n - 1 starting with high - 1 ; store the value and decrement high by 1 ; print the resultant sequence ; 
def LargestArray(N, low, high):
    high_index = N - (high - low + 1)
    if (high_index > (N - 1) // 2):
        print("Not Possible")
        return
    if (high_index <= 0):
        high_index = 1
    A = [0] * N
    temp = high
    for i in range(high_index, -1, -1):
        A[i] = temp
        temp = temp - 1
    high -= 1
    for i in range(high_index + 1, N):
        A[i] = high
        high = high - 1
    for i in range(N):
        print(A[i], end=" ")


N = 5
low = 2
high = 6
LargestArray(N, low, high)

# Expected output:
5 6 5 4 3
# print matrix elements from top | function to traverse the matrix diagonally upwards ; stores the maximum size of vector from all row of matrix nums [ ] [ ] ; store elements in desired order ; store every element on the basis of sum of index ( i + j ) ; print the stored result ; reverse all sublist ; 
def printDiagonalTraversal(nums):
    max_size = len(nums)
    for i in range(len(nums)):
        if (max_size < len(nums[i])):
            max_size = len(nums[i])
    v = [[]for i in range(2 * max_size - 1)]
    for i in range(len(nums)):
        for j in range(len(nums[i])):
            v[i + j].append(nums[i][j])
    for i in range(len(v)):
        v[i] = v[i][::-1]
        for j in range(len(v[i])):
            print(v[i][j], end=" ")


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

# Expected output:
1 4 2 7 5 3 8 6 9
# check if given string satisfies the following conditions | python3 program for the above approach ; function to check if given string satisfies the given conditions ; dimensions ; left diagonal ; right diagonal ; conditions not satisfied ; print yes ; 

import math


def isValid(s):
    n = int(math .sqrt(len(s)))
    check = s[0]
    for i in range(n):
        x = i
        y = i
        while (x >= 0 and y < n):
            if (s[n * x + y] != check or s[n * x + x] != check):
                print("No")
                return
            x -= 1
            y += 1
    print("Yes")


str = "abacdaeaafaghaia"
isValid(str)

# Expected output:
Yes
# sum of all possible strings obtained by removal of non | python 3 program for the above approach ; function to convert a character to its equivalent digit ; function to precompute powers of 10 ; function to precompute prefix sum of numerical strings ; function to return the i - th term of triangular number ; function to return the sum of all resulting strings ; precompute powers of 10 ; precompute prefix sum ; initialize result ; apply the above general formula for every i ; return the answer ; 

N = 10
pref = [0] * N
power = [0] * N


def toDigit(ch):
    return (ord(ch) - ord('0'))


def powerOf10():
    power[0] = 1
    for i in range(1, N):
        power[i] = power[i - 1] * 10


def precomputePrefix(st, n):
    pref[0] = (ord(st[0]) - ord('0'))
    for i in range(1, n):
        pref[i] = (pref[i - 1] + toDigit(st[i]))


def triangularNumber(i):
    res = i * (i + 1) // 2
    return res


def sumOfSubstrings(st):
    n = len(st)
    powerOf10()
    precomputePrefix(st, n)
    ans = 0
    for i in range(n - 1):
        ans += ((pref[n - i - 2] * (i + 1) + toDigit(st[n - i - 1])
                * triangularNumber(n - i - 1)) * power[i])
    return ans


if __name__ == "__main__":
    st = "1234"
    print(sumOfSubstrings(st))

# Expected output:
680
# sum of products of all possible subarrays | function that finds the sum of products of all subarray of arr [ ] ; stores sum of all subarrays ; iterate array from behind ; update the ans ; update the res ; print the final sum ; 
def sumOfSubarrayProd(arr, n):
    ans = 0
    res = 0
    i = n - 1
    while (i >= 0):
        incr = arr[i] * (1 + res)
        ans += incr
        res = incr
        i -= 1
    print(ans)


if __name__ == '__main__':
    arr = [1, 2, 3]
    N = len(arr)
    sumOfSubarrayProd(arr, N)

# Expected output:
20
# sum of all odd length subarrays | function to calculate the sum of all odd length subarrays ; stores the sum ; size of array ; traverse the array ; generate all subarray of odd length ; add the element to sum ; return the final sum ; 
def OddLengthSum(arr):
    sum = 0
    l = len(arr)
    for i in range(l):
        for j in range(i, l, 2):
            for k in range(i, j + 1, 1):
                sum += arr[k]
    return sum


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

# Expected output:
48
# sum of all odd length subarrays | function that finds the sum of all the element of subarrays of odd length ; stores the sum ; size of array ; traverse the given array arr [ ] ; add to the sum for each contribution of the arr [ i ] ; return the final sum ; 
def OddLengthSum(arr):
    Sum = 0
    l = len(arr)
    for i in range(l):
        Sum += ((((i + 1) * (l - i) + 1) // 2) * arr[i])
    return Sum


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

# Expected output:
48
# check if euler totient function is same for a given number and twice of that number | function to find the euler 's totient function ; initialize result as n ; consider all prime factors of n and subtract their multiples from result ; return the count ; function to check if phi ( n ) is equals phi ( 2 * n ) ; 
def phi(n):
    result = 1
    for p in range(2, n):
        if (__gcd(p, n) == 1):
            result += 1
    return result


def __gcd(a, b):
    return a if b == 0 else __gcd(b, a % b)


def sameEulerTotient(n):
    return phi(n) == phi(2 * n)


if __name__ == '__main__':
    N = 13
    if (sameEulerTotient(N)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# check if euler totient function is same for a given number and twice of that number | function to check if phi ( n ) is equals phi ( 2 * n ) ; return if n is odd ; 
def sameEulerTotient(N):
    return (N & 1)


if __name__ == '__main__':
    N = 13
    if (sameEulerTotient(N) == 1):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# smallest occurring element in each subsequence | function that count the subsequence such that each element as the minimum element in the subsequence ; store index in a map ; sort the array ; to store count of subsequence ; traverse the array ; store count of subsequence ; print the count of subsequence ; 
def solve(arr, N):
    M = {}
    for i in range(N):
        M[i] = arr[i]
    arr .sort()
    Count = {}
    for i in range(N):
        Count[arr[i]] = pow(2, N - i - 1)
    for it in Count .values():
        print(it, end=" ")


if __name__ == "__main__":
    arr = [5, 2, 1]
    N = len(arr)
    solve(arr, N)

# Expected output:
4 2 1
# program to insert dashes between two adjacent odd digits in given number | function to check if char ch is odd or not ; function to insert dash - between any 2 consecutive digit in string str ; traverse the string character by character ; compare every consecutive character with the odd value ; print the resultant string ; 
def checkOdd(ch):
    return ((ord(ch) - 48) & 1)


def Insert_dash(num_str):
    result_str = num_str
    x = 0
    while (x < len(num_str) - 1):
        if (checkOdd(num_str[x]) and checkOdd(num_str[x + 1])):
            result_str = (result_str[:x + 1] + '-' + result_str[x + 1:])
            num_str = result_str
            x += 1
        x += 1
    return result_str


str = "1745389"
print(Insert_dash(str))

# Expected output:
1-745-389
# check if a matrix is reverse bitonic or not | python3 program to check if a matrix is reverse bitonic or not ; function to check if an array is reverse bitonic or not ; check for decreasing sequence ; check for increasing sequence ; function to check whether given matrix is bitonic or not ; check row - wise ; check column wise ; generate an array consisting of elements of the current column ; 

N = 3
M = 3


def checkReverseBitonic(arr, n):
    f = 0
    for i in range(1, n):
        if (arr[i] < arr[i - 1]):
            continue
        if (arr[i] == arr[i - 1]):
            return False
        else:
            f = 1
            break
    if (i == n):
        return True
    for j in range(i + 1, n):
        if (arr[j] > arr[j - 1]):
            continue
        if (arr[i] == arr[i - 1]):
            return False
        else:
            if (f == 1):
                return False
    return True


def check(arr):
    f = 0
    for i in range(N):
        if (not checkReverseBitonic(arr[i], M)):
            print("No")
            return
    for i in range(N):
        temp = [0] * N
        for j in range(N):
            temp[j] = arr[j][i]
        if (not checkReverseBitonic(temp, N)):
            print("No")
            return
    print("Yes")


if __name__ == "__main__":
    m = [[2, 3, 4], [1, 2, 3], [4, 5, 6]]
    check(m)

# Expected output:
Yes
# find the element at the specified index of a spirally filled matrix | function to return the element at ( x , y ) ; if y is greater ; if y is odd ; if y is even ; if x is even ; if x is odd ; 
def SpiralElement(x, y):
    r = 0
    if (x < y):
        if (y % 2 == 1):
            r = y * y
            return (r - x + 1)
        else:
            r = (y - 1) * (y - 1)
            return (r + x)
    else:
        if (x % 2 == 0):
            r = x * x
            return (r - y + 1)
        else:
            r = (x - 1) * (x - 1)
            return (r + y)


if __name__ == '__main__':
    x = 2
    y = 3
    print(SpiralElement(x, y))

# Expected output:
8
# make the string in ap by changing a character | function to modify the given string and find the index where modification is needed ; array to store the ascii values of alphabets ; loop to compute the ascii values of characters a - z ; set to store all the possible differences between consecutive elements ; loop to find out the differences between consecutive elements and storing them in the set ; checks if any character of the string disobeys the pattern ; constructing the strings with all possible values of consecutive difference and comparing them with staring string s . ; 
def string_modify(s):
    alphabets = []
    flag, hold_i = 0, 0
    hold_l = s[0]
    for i in range(26):
        alphabets .append(chr(i + ord('a')))
    difference = set()
    reconstruct = ""
    for i in range(1, len(s)):
        difference .add(ord(s[i]) - ord(s[i - 1]))
    if (len(difference) == 1):
        print("No modifications required")
        return
    for it in difference:
        index = ord(s[0]) - ord('a')
        reconstruct = ""
        flag = 0
        i = 0
        while ((i < len(s)) and (flag <= 1)):
            reconstruct += alphabets[index]
            index += it
            if (index < 0):
                index += 26
            index %= 26
            if (reconstruct[i] != s[i]):
                flag += 1
                hold_i = i
                hold_l = s[i]
            i += 1
        if (flag == 1):
            s[hold_i] = reconstruct[hold_i]
            break
    if (flag > 1):
        hold_i = 0
        hold_l = s[0]
        temp = (ord(s[1]) - ord('a') - (ord(s[2]) - ord(s[1]))) % 26
        if (temp < 0):
            temp += 26
        s[0] = alphabets[temp]
    print(hold_i, "->", hold_l)
    print("".join(s))


s = list("aeimqux")
string_modify(s)

# Expected output:
6 -> x
aeimquy
# create matrix whose sum of diagonals in each sub matrix is even | function to prn * n order matrix with all sub - matrix of even order is sum of its diagonal also even ; even index ; odd index ; iterate two nested loop ; for even index the element should be consecutive odd ; for odd index the element should be consecutive even ; 
def evenSubMatrix(N):
    even = 1
    odd = 2
    for i in range(N):
        for j in range(N):
            if ((i + j) % 2 == 0):
                print(even, end=" ")
                even += 2
            else:
                print(odd, end=" ")
                odd += 2
        print()


N = 4
evenSubMatrix(N)

# Expected output:
1 2 3 4 
6 5 8 7 
9 10 11 12 
14 13 16 15
# remove leading zeros from a number given as a string | python3 program to implement the above approach ; function to remove all leading zeros from a a given string ; regex to remove leading zeros from a string ; replaces the matched value with given string ; 

import re


def removeLeadingZeros(str):
    regex = "^0+(?!$)"
    str = re .sub(regex, "", str)
    print(str)


str = "0001234"
removeLeadingZeros(str)

# Expected output:
1234
# maximum inversions in a sequence of 1 to n after performing given operations at most k times | function which computes the maximum number of inversions ; ' answer ' will store the required number of inversions ; we do this because we will never require more than floor ( n / 2 ) operations ; left pointer in the array ; right pointer in the array ; doing k operations ; incrementing ans by number of inversions increase due to this swapping ; 
def maximum_inversion(n, k):
    answer = 0
    k = min(k, n // 2)
    left = 1
    right = n
    while (k > 0):
        k -= 1
        answer += 2 * (right - left) - 1
        left += 1
        right -= 1
    print(answer)


if __name__ == '__main__':
    N = 5
    K = 3
    maximum_inversion(N, K)
    N = 4
    K = 1
    maximum_inversion(N, K)

# Expected output:
10
5
# first number to leave an odd remainder after repetitive division by 2 | python3 program to implement the above approach ; function to return the position least significant set bit ; function return the first number to be converted to an odd integer ; stores the positions of the first set bit ; if both are same ; if a has the least significant set bit ; otherwise ; 

from math import log


def getFirstSetBitPos(n):
    return log(n & -n, 2) + 1


def oddFirst(a, b):
    steps_a = getFirstSetBitPos(a)
    steps_b = getFirstSetBitPos(b)
    if (steps_a == steps_b):
        return -1
    if (steps_a > steps_b):
        return b
    if (steps_a < steps_b):
        return a


if __name__ == '__main__':
    a = 10
    b = 8
    print(oddFirst(a, b))

# Expected output:
10