giulio98/xlcost-single-prompt huggingface dataset:
# arithmetic progression containing x and y with least possible first term | python3 program for the approach ; function that finds the minimum positive first term including x with given common difference and the number of terms ; stores the first term ; initialize the low and high ; perform binary search ; find the mid ; check if first term is greater than 0 ; store the possible first term ; search between mid + 1 to high ; search between low to mid - 1 ; return the minimum first term ; function that finds the arithmetic progression with minimum possible first term containing x and y ; considering x to be smaller than y always ; stores the max common difference ; stores the minimum first term and the corresponding common difference of the resultant ap ; iterate over all the common difference ; check if x and y is included for current common difference ; store the possible common difference ; number of terms from x to y with diff1 common difference ; number of terms from x to y with diff2 common difference ; find the corresponding first terms with diff1 and diff2 ; store the minimum first term and the corresponding common difference ; print the resultant ap ; 

import sys


def minFirstTerm(X, diff, N):
    first_term_1 = sys .maxsize
    low = 0
    high = N
    while (low <= high):
        mid = (low + high) // 2
        if (X - mid * diff > 0):
            first_term_1 = X - mid * diff
            low = mid + 1
        else:
            high = mid - 1
    return first_term_1


def printAP(N, X, Y):
    if (X > Y):
        X = X + Y
        Y = X - Y
        X = X - Y
    maxDiff = Y - X
    first_term = sys .maxsize
    diff = 0
    for i in range(1, maxDiff + 1):
        if i * i > maxDiff:
            break
        if (maxDiff % i == 0):
            diff1 = i
            diff2 = maxDiff // diff1
            terms1 = diff2 + 1
            terms2 = diff1 + 1
            first_term1 = minFirstTerm(X, diff1, N - terms1)
            first_term2 = minFirstTerm(X, diff2, N - terms2)
            if (first_term1 < first_term):
                first_term = first_term1
                diff = diff1
            if (first_term2 < first_term):
                first_term = first_term2
                diff = diff2
    for i in range(N):
        print(first_term, end=" ")
        first_term += diff


if __name__ == '__main__':
    N = 5
    X = 10
    Y = 15
    printAP(N, X, Y)

# Expected output:
5 10 15 20 25
# check if a number can be represented as sum of two consecutive perfect cubes | function to check if a number can be expressed as the sum of cubes of two consecutive numbers ; 
def isCubeSum(n):
    for i in range(1, int(pow(n, 1 / 3)) + 1):
        if (i * i * i + (i + 1) * (i + 1) * (i + 1) == n):
            return True
    return False


if __name__ == '__main__':
    n = 35
    if (isCubeSum(n)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# check if a number can be represented as sum of two consecutive perfect cubes | function to check that a number is the sum of cubes of 2 consecutive numbers or not ; condition to check if a number is the sum of cubes of 2 consecutive numbers or not ; 
def isSumCube(N):
    a = int(pow(N, 1 / 3))
    b = a - 1
    ans = ((a * a * a + b * b * b) == N)
    return ans


i = 35
if (isSumCube(i)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# maximize sum of remaining elements after every removal of the array half with greater sum | function to find the maximum sum ; base case len of array is 1 ; stores the final result ; traverse the array ; store left prefix sum ; store right prefix sum ; compare the left and right ; if both are equal apply the optimal method ; update with minimum ; return the final ans ; function to print maximum sum ; dicitionary to store prefix sums ; traversing the array ; add prefix sum of the array ; 
def maxweight(s, e, pre):
    if s == e:
        return 0
    ans = 0
    for i in range(s, e):
        left = pre[i] - pre[s - 1]
        right = pre[e] - pre[i]
        if left < right:
            ans = max(ans, left + maxweight(s, i, pre))
        if left == right:
            ans = max(
                ans,
                left +
                maxweight(
                    s,
                    i,
                    pre),
                right +
                maxweight(
                    i +
                    1,
                    e,
                    pre))
        if left > right:
            ans = max(ans, right + maxweight(i + 1, e, pre))
    return ans


def maxSum(arr):
    pre = {-1: 0, 0: arr[0]}
    for i in range(1, len(arr)):
        pre[i] = pre[i - 1] + arr[i]
    print(maxweight(0, len(arr) - 1, pre))


arr = [6, 2, 3, 4, 5, 5]
maxSum(arr)

# Expected output:
18
# maximum time in hh : mm : ss format that can be represented by given six digits | function to return the maximum possible time in 24 - hours format that can be represented by array elements ; stores the frequency of the array elements ; maximum possible time ; iterate to minimum possible time ; conditions to reduce the the time iteratively ; if all required digits are present in the map ; retrieve original count ; if seconds is reduced to 0 ; if minutes is reduced to 0 ; 
def largestTimeFromDigits(A):
    mp1 = {}
    mp2 = {}
    for x in A:
        mp1[x] = mp1 .get(x, 0) + 1
    mp2 = mp1 .copy()
    hr = 23
    m = 59
    s = 59
    while (hr >= 0):
        h0 = hr // 10
        h1 = hr % 10
        m0 = m // 10
        m1 = m % 10
        s0 = s // 10
        s1 = s % 10
        p = 0
        arr = [h0, h1, m0, m1, s0, s1]
        for it in arr:
            if (it in mp1 and mp1 .get(it) > 0):
                mp1[it] = mp1 .get(it) - 1
            else:
                p = 1
        if (p == 0):
            s = ""
            s = (str(h0) + str(h1))
            s += (':' + str(m0) + str(m1))
            s += (':' + str(s0) + str(s1))
            return s
        mp1 = mp2 .copy()
        if (s == 0):
            s = 59
            m -= 1
        elif (m < 0):
            m = 59
            hr -= 1
        if (s > 0):
            s -= 1
    return "-1"


if __name__ == '__main__':
    v = [0, 2, 1, 9, 3, 2]
    print(largestTimeFromDigits(v))

# Expected output:
23:29:10
# minimum size substring to be removed to make a given string palindromic | function to find palindromic prefix of maximum length ; finding palindromic prefix of maximum length ; checking if curr substring is palindrome or not . ; condition to check if the prefix is a palindrome ; if no palindrome exist ; function to find the maximum size palindrome such that after removing minimum size substring ; finding prefix and suffix of same length ; matching the ranges ; case 1 : length is even and whole string is palindrome ; case 2 : length is odd and whole string is palindrome ; adding that mid character ; add prefix or suffix of the remaining string or suffix , whichever is longer ; reverse the remaining string to find the palindromic suffix ; 
def palindromePrefix(S):
    n = len(S)
    for i in range(n - 1, -1, -1):
        curr = S[0:i + 1]
        l = 0
        r = len(curr) - 1
        is_palindrome = 1
        while (l < r):
            if (curr[l] != curr[r]):
                is_palindrome = 0
                break
            l += 1
            r -= 1
        if (is_palindrome):
            return curr
    return ""


def maxPalindrome(S):
    n = len(S)
    if (n <= 1):
        return S
    pre = ""
    suff = ""
    i = 0
    j = n - 1
    while (S[i] == S[j] and i < j):
        i += 1
        j -= 1
    i -= 1
    j += 1
    pre = S[0:i + 1]
    suff = S[j:]
    if (j - i == 1):
        return pre + suff
    if (j - i == 2):
        mid_char = S[i + 1:i + 2]
        return pre + mid_char + suff
    rem_str = S[i + 1:j]
    pre_of_rem_str = palindromePrefix(rem_str)
    list1 = list(rem_str)
    list1 .reverse()
    rem_str = ''.join(list1)
    suff_of_rem_str = palindromePrefix(rem_str)
    if (len(pre_of_rem_str) >= len(suff_of_rem_str)):
        return (pre + pre_of_rem_str + suff)
    else:
        return (pre + suff_of_rem_str + suff)


if __name__ == "__main__":
    S = "geeksforskeeg"
    print(maxPalindrome(S))

# Expected output:
geeksfskeeg
# count numbers from a given range that contains a given number as the suffix | python3 program of the above approach ; function to count the number ends with given number in range ; find number of digits in a ; find the power of 10 ; incrementing the a ; 

from math import log10


def countNumEnds(A, L, R):
    count = 0
    digits = int(log10(A) + 1)
    temp = int(pow(10, digits))
    cycle = temp
    while (temp <= R):
        if (temp >= L):
            count += 1
        temp += cycle
    print(count)


A = 2
L = 2
R = 20
countNumEnds(A, L, R)

# Expected output:
2
# minimize replacement of characters to its nearest alphabet to make a string palindromic | function to find the minimum number of operations required to convert th given string into palindrome ; iterate till half of the string ; find the absolute difference between the characters ; adding the minimum difference of the two result ; return the result ; 
def minOperations(s):
    length = len(s)
    result = 0
    for i in range(length // 2):
        D1 = (ord(max(s[i], s[length - 1 - i])) -
              ord(min(s[i], s[length - 1 - i])))
        D2 = 26 - D1
        result += min(D1, D2)
    return result


s = "abccdb"
print(minOperations(s))

# Expected output:
3
# check if all the pairs of an array are coprime with each other | function to store and check the factors ; check if factors are equal ; check if the factor is already present ; insert the factor in set ; check if the factor is already present ; insert the factors in set ; function to check if all the pairs of array elements are coprime with each other ; check if factors of a [ i ] haven 't occurred previously ; 
def findFactor(value, factors):

    factors.add(value)
    i = 2
    while (i * i <= value):

        if value % i == 0:
            if value // i == i:
                if i in factors:
                    return bool(True)
                else:
                    factors.add(i)
            else:
                if (i in factors) or ((value // i) in factors):
                    return bool(True)
                else:
                    factors.add(i)
                    factors.add(value // i)

        i += 1
    return bool(False)


def allCoprime(A, n):

    all_coprime = bool(True)
    factors = set()

    for i in range(n):
        if A[i] == 1:
            continue
        if findFactor(A[i], factors):
            all_coprime = bool(False)
            break

    return bool(all_coprime)


A = [3, 5, 11, 7, 19]
arr_size = len(A)
if (allCoprime(A, arr_size)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# count subsequences which contains both the maximum and minimum array element | function to calculate the count of subsequences ; find the maximum from the array ; find the minimum from the array ; if array contains only one distinct element ; find the count of maximum ; find the count of minimum ; finding the result with given condition ; 
def countSubSequence(arr, n):
    maximum = max(arr)
    minimum = min(arr)
    if maximum == minimum:
        return pow(2, n) - 1
    i = arr .count(maximum)
    j = arr .count(minimum)
    res = (pow(2, i) - 1) * (pow(2, j) - 1) * pow(2, n - i - j)
    return res


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

# Expected output:
4
# minimize elements to be added to a given array such that it contains another given array as its subsequence | function that finds the minimum number of the element must be added to make a as a subsequence in b ; base case ; dp [ i ] [ j ] indicates the length of lcs of a of length i & b of length j ; if there are no elements either in a or b then the length of lcs is 0 ; if the element present at ith and jth index of a and b are equal then include in lcs ; if they are not equal then take the max ; return difference of length of a and lcs of a and b ; 
def transformSubsequence(n, m, A, B):
    if B is None or len(B) == 0:
        return n
    dp = [[0 for col in range(m + 1)]for row in range(n + 1)]
    for i in range(n + 1):
        for j in range(m + 1):
            if i == 0 or j == 0:
                dp[i][j] = 0
            elif A[i - 1] == B[j - 1]:
                dp[i][j] = 1 + dp[i - 1][j - 1]
            else:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
    return n - dp[n][m]


if __name__ == "__main__":
    N = 5
    M = 6
    A = [1, 2, 3, 4, 5]
    B = [2, 5, 6, 4, 9, 12]
    print(transformSubsequence(N, M, A, B))

# Expected output:
3
# check if the sum of a subarray within a given range is a perfect square or not | function to calculate the square root of the sum of a subarray in a given range ; calculate the sum of array elements within a given range ; finding the square root ; if a perfect square is found ; reduce the search space if the value is greater than sum ; reduce the search space if the value if smaller than sum ; 
def checkForPerfectSquare(arr, i, j):
    mid, sum = 0, 0
    for m in range(i, j + 1):
        sum += arr[m]
    low = 0
    high = sum // 2
    while (low <= high):
        mid = low + (high - low) // 2
        if (mid * mid == sum):
            return mid
        elif (mid * mid > sum):
            high = mid - 1
        else:
            low = mid + 1
    return -1


if __name__ == '__main__':
    arr = [2, 19, 33, 48, 90, 100]
    L = 1
    R = 3
    print(checkForPerfectSquare(arr, L, R))

# Expected output:
10
# count of subarrays forming an arithmetic progression ( ap ) | function to find the total count of subarrays ; iterate over each subarray ; difference between first two terms of subarray ; iterate over the subarray from i to j ; check if the difference of all adjacent elements is same ; 
def calcSubarray(A, N):
    count = 0
    for i in range(N):
        for j in range(i + 1, N):
            flag = True
            comm_diff = A[i + 1] - A[i]
            for k in range(i, j):
                if (A[k + 1] - A[k] == comm_diff):
                    continue
                else:
                    flag = False
                    break
            if (flag):
                count += 1
    return count


if __name__ == '__main__':
    A = [8, 7, 4, 1, 0]
    N = len(A)
    print(calcSubarray(A, N))

# Expected output:
5
# largest sum contiguous subarray having unique elements | function to calculate required maximum subarray sum ; initialize two pointers ; stores the unique elements ; insert the first element ; current max sum ; global maximum sum ; update sum & increment j ; add the current element ; update sum and increment i and remove arr [ i ] from set ; remove the element from start position ; return the maximum sum ; 
def maxSumSubarray(arr):
    i = 0
    j = 1
    set = {}
    set[arr[0]] = 1
    sum = arr[0]
    maxsum = sum
    while (i < len(arr) - 1 and j < len(arr)):
        if arr[j]not in set:
            sum = sum + arr[j]
            maxsum = max(sum, maxsum)
            set[arr[j]] = 1
            j += 1
        else:
            sum -= arr[i]
            del set[arr[i]]
            i += 1
    return maxsum


if __name__ == '__main__':
    arr = [1, 2, 3, 1, 5]
    ans = maxSumSubarray(arr)
    print(ans)

# Expected output:
11
# count of numbers having only one unset bit in a range [ l , r ] | python3 program for the above approach ; function to count numbers in the range [ l , r ] having exactly one unset bit ; stores the required count ; iterate over the range ; calculate number of bits ; calculate number of set bits ; if count of unset bits is 1 ; increment answer ; return the answer ; 

from math import log2


def count_numbers(L, R):
    ans = 0
    for n in range(L, R + 1):
        no_of_bits = int(log2(n) + 1)
        no_of_set_bits = bin(n).count('1')
        if (no_of_bits - no_of_set_bits == 1):
            ans += 1
    return ans


if __name__ == '__main__':
    L = 4
    R = 9
    print(count_numbers(L, R))

# Expected output:
2
# count of numbers having only one unset bit in a range [ l , r ] | python3 program for the above approach ; function to count numbers in the range [ l , r ] having exactly one unset bit ; stores the count elements having one zero in binary ; stores the maximum number of bits needed to represent number ; loop over for zero bit position ; number having zero_bit as unset and remaining bits set ; sets all bits before zero_bit ; set the bit at position j ; set the bit position at j ; if cur is in the range [ l , r ] , then increment ans ; return ans ; 

import math


def count_numbers(L, R):
    ans = 0
    LogR = (int)(math .log(R) + 1)
    for zero_bit in range(LogR):
        cur = 0
        for j in range(zero_bit):
            cur |= (1 << j)
        for j in range(zero_bit + 1, LogR):
            cur |= (1 << j)
            if (cur >= L and cur <= R):
                ans += 1
    return ans


if __name__ == '__main__':
    L = 4
    R = 9
    print(count_numbers(L, R))

# Expected output:
2
# sum of all distances between occurrences of same characters in a given string | function to calculate the sum of distances between occurrences of same characters in a string ; if similar characters are found ; add the difference of their positions ; return the answer ; 
def findSum(s):
    sum = 0
    for i in range(len(s)):
        for j in range(i + 1, len(s)):
            if (s[i] == s[j]):
                sum += (j - i)
    return sum


s = "ttt"
print(findSum(s))

# Expected output:
4
# count array elements that can be represented as sum of at least two consecutive array elements | function to find the number of array elements that can be represented as the sum of two or more consecutive array elements ; stores the frequencies of array elements ; stores required count ; update frequency of each array element ; find sum of all subarrays ; increment ans by cnt [ sum ] ; reset cnt [ sum ] by 0 ; return ans ; 
def countElements(a, n):
    cnt = [0] * (n + 1)
    ans = 0
    for k in a:
        cnt[k] += 1
    for l in range(n):
        sum = 0
        for r in range(l, n):
            sum += a[r]
            if (l == r):
                continue
            if (sum <= n):
                ans += cnt[sum]
                cnt[sum] = 0
    return ans


if __name__ == '__main__':
    a = [1, 1, 1, 1, 1]
    print(countElements(a, len(a)))

# Expected output:
0
# maximum gcd among all pairs ( i , j ) of first n natural numbers | python3 program for the above approach ; function to find maximum gcd of all pairs possible from first n natural numbers ; stores maximum gcd ; iterate over all possible pairs ; update maximum gcd ; 
def __gcd(a, b):
    if (b == 0):
        return a
    else:
        return __gcd(b, a % b)


def maxGCD(n):
    maxHcf = -2391734235435
    for i in range(1, n + 1):
        for j in range(i + 1, n + 1):
            maxHcf = max(maxHcf, __gcd(i, j))
    return maxHcf


if __name__ == '__main__':
    n = 4
    print(maxGCD(n))

# Expected output:
2
# maximum gcd among all pairs ( i , j ) of first n natural numbers | function to find the maximum gcd among all the pairs from first n natural numbers ; return max gcd ; 
def maxGCD(n):
    return (n // 2)


if __name__ == '__main__':
    n = 4
    print(maxGCD(n))

# Expected output:
2
# remove odd indexed characters from a given string | function to remove the odd indexed characters from a given string ; stores the resultant string ; if the current index is odd ; skip the character ; otherwise , append the character ; return the modified string ; 
def removeOddIndexCharacters(s):
    new_s = ""
    i = 0
    while i < len(s):
        if (i % 2 == 1):
            i += 1
            continue
        new_s += s[i]
        i += 1
    return new_s


if __name__ == '__main__':
    str = "abcdef"
    str = removeOddIndexCharacters(str)
    print(str)

# Expected output:
ace
# longest subarray forming a geometic progression ( gp ) | function to return the length of the longest subarray forming a gp in a sorted array ; base case ; stores the length of gp and the common ratio ; stores the maximum length of the gp ; traverse the array ; check if the common ratio is valid for gp ; if the current common ratio is equal to previous common ratio ; increment the length of the gp ; store the max length of gp ; otherwise ; update the common ratio ; update the length of gp ; store the max length of gp ; update the length of gp ; store the max length of gp ; return the max length of gp ; 
def longestGP(A, N):
    if (N < 2):
        return N
    length = 1
    common_ratio = 1
    maxlength = 1
    for i in range(N - 1):
        if (A[i + 1] % A[i] == 0):
            if (A[i + 1] // A[i] == common_ratio):
                length = length + 1
                maxlength = max(maxlength, length)
            else:
                common_ratio = A[i + 1] // A[i]
                length = 2
        else:
            maxlength = max(maxlength, length)
            length = 1
    maxlength = max(maxlength, length)
    return maxlength


arr = [1, 2, 4, 7, 14, 28, 56, 89]
N = len(arr)
print(longestGP(arr, N))

# Expected output:
4
# maximum number of uncrossed lines between two given arrays | function to count maximum number of uncrossed lines between the two given arrays ; stores the length of lcs obtained upto every index ; iterate over first array ; iterate over second array ; update value in dp table ; if both characters are equal ; update the length of lcs ; if both characters are not equal ; update the table ; return the answer ; 
def uncrossedLines(a, b, n, m):
    dp = [[0 for x in range(m + 1)]for y in range(n + 1)]
    for i in range(n + 1):
        for j in range(m + 1):
            if (i == 0 or j == 0):
                dp[i][j] = 0
            elif (a[i - 1] == b[j - 1]):
                dp[i][j] = 1 + dp[i - 1][j - 1]
            else:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
    return dp[n][m]


if __name__ == "__main__":
    A = [3, 9, 2]
    B = [3, 2, 9]
    N = len(A)
    M = len(B)
    print(uncrossedLines(A, B, N, M))

# Expected output:
2
# minimize flips required to make all shortest paths from top | function to count the minimum number of flips required ; dimensions of matrix ; stores the count the flips ; check if element is same or not ; return the final count ; given matrix ; 
def minFlips(mat, s):
    N = len(mat)
    M = len(mat[0])
    count = 0
    for i in range(N):
        for j in range(M):
            if (mat[i][j] != ord(s[i + j]) - ord('0')):
                count += 1
    return count


mat = [[1, 0, 1], [0, 1, 1], [0, 0, 0]]
s = "10001"
print(minFlips(mat, s))

# Expected output:
4
# generate a pair of integers from a range [ l , r ] whose lcm also lies within the range | python3 implementation of the above approach ; checking if any pair is possible or not in range ( l , r ) ; if not possible print ( - 1 ) ; print lcm pair ; 
def lcmpair(l, r):
    x = l
    y = 2 * l
    if (y > r):
        print(-1)
    else:
        print("X = {} Y = {}".format(x, y))


l = 13
r = 69
lcmpair(l, r)

# Expected output:
X = 13 Y = 26
# count non | function to reverse a number ; store the reverse of n ; return reverse of n ; function to get the count of non - palindromic numbers having same first and last digit ; store the required count ; traverse the array ; store reverse of arr [ i ] ; check for palindrome ; if non - palindromic ; check if first and last digits are equal ; 
def revNum(N):
    x = 0
    while (N):
        x = x * 10 + N % 10
        N = N // 10
    return x


def ctNonPalin(arr, N):
    Res = 0
    for i in range(N):
        x = revNum(arr[i])
        if (x == arr[i]):
            continue
        else:
            Res += (arr[i] % 10 == N % 10)
    return Res


if __name__ == '__main__':
    arr = [121, 134, 2342, 4514]
    N = len(arr)
    print(ctNonPalin(arr, N))

# Expected output:
2