giulio98/xlcost-single-prompt huggingface dataset:
# minimum number of steps required to reach origin from a given point | function to find the minimum moves required to reach origin from ( a , b ) ; stores the minimum number of moves ; check if the absolute difference is 1 or 0 ; store the minimum of a , b ; store the maximum of a , b ; prthe answer ; 
def findMinMoves(a, b):
    ans = 0
    if (a == b or abs(a - b) == 1):
        ans = a + b
    else:
        k = min(a, b)
        j = max(a, b)
        ans = 2 * k + 2 * (j - k) - 1
    print(ans)


if __name__ == '__main__':
    a, b = 3, 5
    findMinMoves(a, b)

# Expected output:
9
# count even sum pairs possible by selecting two integers from two given ranges respectively | function to count even sum pairs in the given range ; stores the count of even numbers between 1 to x ; stores the count of odd numbers between 1 to x ; stores the count of even numbers between 1 to y ; stores the count of odd numbers between 1 to y ; stores the count of pairs having even sum ; returns the count of pairs having even sum ; 
def cntEvenSumPairs(X, Y):
    cntXEvenNums = X / 2
    cntXOddNums = (X + 1) / 2
    cntYEvenNums = Y / 2
    cntYOddNums = (Y + 1) / 2
    cntPairs = ((cntXEvenNums * cntYEvenNums) + (cntXOddNums * cntYOddNums))
    return cntPairs


X = 2
Y = 3
print(cntEvenSumPairs(X, Y))

# Expected output:
4.5
# minimize array elements required to be incremented or decremented to convert given array into a fibonacci series | python3 program for the above approach ; function to calculate minimum number of moves to make the sequence a fibonacci series ; if number of elements is less than 3 ; initialize the value of the result ; try all permutations of the first two elements ; value of first element after operation ; value of second element after operation ; calculate number of moves for rest of the elements of the array ; element at idx index ; if it is not possible to change the element in atmost one move ; otherwise ; update the answer ; return the answer ; 

import sys


def minMoves(arr):
    N = len(arr)
    if (N <= 2):
        return 0
    ans = sys .maxsize
    for i in range(-1, 2):
        for j in range(-1, 2):
            num1 = arr[0] + i
            num2 = arr[1] + j
            flag = 1
            moves = abs(i) + abs(j)
            for idx in range(2, N):
                num = num1 + num2
                if (abs(arr[idx] - num) > 1):
                    flag = 0
                else:
                    moves += abs(arr[idx] - num)
                num1 = num2
                num2 = num
            if (flag):
                ans = min(ans, moves)
    if (ans == sys .maxsize):
        return -1
    return ans


if __name__ == "__main__":
    arr = [4, 8, 9, 17, 27]
    print(minMoves(arr))

# Expected output:
3
# queries to calculate sum of array elements present at every yth index starting from the index x | function to find the sum of arr [ x ] + arr [ x + y ] + arr [ x + 2 * y ] + ... for all queries ; iterate over each query ; stores the sum of arr [ x ] + arr [ x + y ] + arr [ x + 2 * y ] + ... ; traverse the array and calculate the sum of the expression ; update sum ; update x ; 
def querySum(arr, N, Q, M):
    for i in range(M):
        x = Q[i][0]
        y = Q[i][1]
        sum = 0
        while (x < N):
            sum += arr[x]
            x += y
        print(sum, end=" ")


if __name__ == '__main__':
    arr = [1, 2, 7, 5, 4]
    Q = [[2, 1], [3, 2]]
    N = len(arr)
    M = len(Q)
    querySum(arr, N, Q, M)

# Expected output:
16 5
# calculate bitwise or of two integers from their given bitwise and and bitwise xor values | function to calculate bitwise or from given bitwise xor and bitwise and values ; 
def findBitwiseORGivenXORAND(X, Y):
    return X + Y


if __name__ == "__main__":
    X = 5
    Y = 2
    print(findBitwiseORGivenXORAND(X, Y))

# Expected output:
7
# check if a given value can be reached from another value in a circular queue by k | function to return gcd of two numbers a and b ; base case ; recursively find the gcd ; function to check of b can be reaced from a with a jump of k elements in the circular queue ; find gcd of n and k ; if a - b is divisible by gcd then pryes ; otherwise ; 
def GCD(a, b):
    if (b == 0):
        return a
    return GCD(b, a % b)


def canReach(N, A, B, K):
    gcd = GCD(N, K)
    if (abs(A - B) % gcd == 0):
        print("Yes")
    else:
        print("No")


if __name__ == '__main__':
    N = 5
    A = 2
    B = 1
    K = 2
    canReach(N, A, B, K)

# Expected output:
Yes
# count of subarrays having sum equal to its length | set 2 | python3 program for the above approach ; function that counts the subarrays with sum of its elements as its length ; store count of elements upto current element with length i ; stores the final count of subarray ; stores the prefix sum ; if size of subarray is 1 ; iterate the array ; find the sum ; update frequency in map ; print the total count ; 

from collections import defaultdict


def countOfSubarray(arr, N):
    mp = defaultdict(lambda: 0)
    answer = 0
    sum = 0
    mp[1] += 1
    for i in range(N):
        sum += arr[i]
        answer += mp[sum - i]
        mp[sum - i] += 1
    print(answer)


if __name__ == '__main__':
    arr = [1, 0, 2, 1, 2, -2, 2, 4]
    N = len(arr)
    countOfSubarray(arr, N)

# Expected output:
7
# split first n natural numbers into two sets with minimum absolute difference of their sums | function to split the first n natural numbers into two sets having minimum absolute difference of their sums ; stores the sum of elements of set1 ; stores the sum of elements of set2 ; traverse first n natural numbers ; check if sum of elements of set1 is less than or equal to sum of elements of set2 ; 
def minAbsDiff(N):
    sumSet1 = 0
    sumSet2 = 0
    for i in reversed(range(N + 1)):
        if sumSet1 <= sumSet2:
            sumSet1 = sumSet1 + i
        else:
            sumSet2 = sumSet2 + i
    return abs(sumSet1 - sumSet2)


N = 6
print(minAbsDiff(N))

# Expected output:
1
# check if a number is prime in flipped upside down , mirror flipped and mirror flipped upside down | function to check if n contains digits 0 , 1 , 2 , 5 , 8 only ; extract digits of n ; return false if any of these digits are present ; function to check if n is prime or not ; check for all factors ; function to check if n is prime in all the desired forms ; 
def checkDigits(n):
    while True:
        r = n % 10
        if (r == 3 or r == 4 or r == 6 or r == 7 or r == 9):
            return False
        n //= 10
        if n == 0:
            break
    return True


def isPrime(n):
    if (n <= 1):
        return False
    for i in range(2, n + 1):
        if i * i > n:
            break
        if (n % i == 0):
            return False
    return True


def isAllPrime(n):
    return isPrime(n) and checkDigits(n)


if __name__ == '__main__':
    N = 101
    if (isAllPrime(N)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# minimum cost required to generate a balanced bracket sequence | function to calculate the minimum cost required to generate a balanced bracket sequence ; stores the count of unbalanced open brackets ; stores the count of unbalanced closed brackets ; stores the count of open brackets ; stores the count of closed brackets ; if open brace is encountered ; otherwise ; if no unbalanced open brackets are present ; increase count of unbalanced closed brackets ; otherwise ; reduce count of unbalanced open brackets ; increase count of closed brackets ; calculate lower bound of minimum cost ; reduce excess open or closed brackets to prevent counting them twice ; update answer by adding minimum of removing both unbalanced open and closed brackets or inserting closed unbalanced brackets to end of string ; prthe result ; 
def minCost(str, a, b):
    openUnbalanced = 0
    closedUnbalanced = 0
    openCount = 0
    closedCount = 0
    for i in range(len(str)):
        if (str[i] == '('):
            openUnbalanced += 1
            openCount += 1
        else:
            if (openUnbalanced == 0):
                closedUnbalanced += 1
            else:
                openUnbalanced -= 1
            closedCount += 1
    result = a * (abs(openCount - closedCount))
    if (closedCount > openCount):
        closedUnbalanced -= (closedCount - openCount)
    if (openCount > closedCount):
        openUnbalanced -= (openCount - closedCount)
    result += min(a * (openUnbalanced + closedUnbalanced),
                  b * closedUnbalanced)
    print(result)


if __name__ == '__main__':
    str = "))()(()()("
    A = 1
    B = 3
    minCost(str, A, B)

# Expected output:
4
# count of permutations such that sum of k numbers from given range is even | function to return the number of all permutations such that sum of k numbers in range is even ; find total count of even and odd number in given range ; iterate loop k times and update even_sum & odd_sum using previous values ; update the prev_even and odd_sum ; even sum ; odd sum ; return even_sum ; 
def countEvenSum(low, high, k):
    even_count = high / 2 - (low - 1) / 2
    odd_count = (high + 1) / 2 - low / 2
    even_sum = 1
    odd_sum = 0
    for i in range(0, k):
        prev_even = even_sum
        prev_odd = odd_sum
        even_sum = ((prev_even * even_count) + (prev_odd * odd_count))
        odd_sum = ((prev_even * odd_count) + (prev_odd * even_count))
    print(int(even_sum))


low = 4
high = 5
K = 3
countEvenSum(low, high, K)

# Expected output:
4
# count of n digit numbers whose sum of every k consecutive digits is equal | set 2 | function to count the number of n - digit numbers such that sum of every k consecutive digits are equal ; print the answer ; 
def count(n, k):
    count = (pow(10, k) - pow(10, k - 1))
    print(count)


if __name__ == '__main__':
    n = 2
    k = 1
    count(n, k)

# Expected output:
9
# sum of largest divisor of numbers upto n not divisible by given prime number p | function to find the sum of largest divisors of numbers in range 1 to n not divisible by prime number p ; total sum upto n ; if no multiple of p exist up to n ; if only p itself is in the range from 1 to n ; sum of those that are divisible by p ; recursively function call to find the sum for n / p ; 
def func(N, P):
    sumUptoN = (N * (N + 1) / 2)
    sumOfMultiplesOfP = 0
    if (N < P):
        return sumUptoN
    elif ((N / P) == 1):
        return sumUptoN - P + 1
    sumOfMultiplesOfP = (((N / P) * (2 * P + (N / P - 1) * P)) / 2)
    return (sumUptoN + func(N / P, P) - sumOfMultiplesOfP)


if __name__ == '__main__':
    N = 10
    P = 5
    print(func(N, P))

# Expected output:
43.0
# count of right shifts for each array element to be in its sorted position | function to find the right shifts required for each element to reach its sorted array position in a [ ] ; stores required number of shifts for each element ; if the element is at sorted position ; otherwise ; calculate right shift ; print the respective shifts ; 
def findShifts(A, N):
    shift = [0 for i in range(N)]
    for i in range(N):
        if (i == A[i] - 1):
            shift[i] = 0
        else:
            shift[i] = (A[i] - 1 - i + N) % N
    for i in range(N):
        print(shift[i], end=" ")


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

# Expected output:
0 2 0 3 0
# construct a matrix with sum equal to the sum of diagonal elements | function to construct matrix with diagonal sum equal to matrix sum ; if diagonal position ; positive element ; negative element ; 
def constructmatrix(N):
    check = bool(True)
    for i in range(N):
        for j in range(N):
            if (i == j):
                print(1, end=" ")
            elif (check):
                print(2, end=" ")
                check = bool(False)
            else:
                print(-2, end=" ")
                check = bool(True)
        print()


N = 5
constructmatrix(5)

# Expected output:
1 2 -2 2 -2 
2 1 -2 2 -2 
2 -2 1 2 -2 
2 -2 2 1 -2 
2 -2 2 -2 1
# minimum count of numbers required with unit digit x that sums up to n | function to calculate and return the minimum number of times a number with unit digit x needs to be added to get a sum n ; calculate the number of additions required to get unit digit of n ; if unit digit of n cannot be obtained ; function to return the minimum number required to represent n ; stores unit digit of n ; stores minimum addition of x required to obtain unit digit of n ; if unit digit of n cannot be obtained ; otherwise ; if n is greater than or equal to ( x * times ) ; minimum count of numbers that needed to represent n ; representation not possible ; 
def check(unit_digit, X):
    for times in range(1, 11):
        digit = (X * times) % 10
        if (digit == unit_digit):
            return times
    return -1


def getNum(N, X):
    unit_digit = N % 10
    times = check(unit_digit, X)
    if (times == -1):
        return times
    else:
        if (N >= (times * X)):
            return times
        else:
            return -1


N = 58
X = 7
print(getNum(N, X))

# Expected output:
4
# minimum number of points required to cover all blocks of a 2 | function to find the minimum number of points required to cover a grid ; if number of block is even ; return the minimum points ; 
def minPoints(n, m):
    ans = 0
    if ((n % 2 != 0) and (m % 2 != 0)):
        ans = ((n * m) // 2) + 1
    else:
        ans = (n * m) // 2
    return ans


if __name__ == '__main__':
    N = 5
    M = 7
    print(minPoints(N, M))

# Expected output:
18
# largest lexicographical string with at most k consecutive elements | function to find the largest lexicographical string with given constraints . ; vector containing frequency of each character . ; assigning frequency to ; empty string of string class type ; loop to iterate over maximum priority first . ; if frequency is greater than or equal to k . ; temporary variable to operate in - place of k . ; concatenating with the resultant string ans . ; handling k case by adjusting with just smaller priority element . ; condition to verify if index j does have frequency greater than 0 ; ; if no such element is found than string can not be processed further . ; if frequency is greater than 0 and less than k . ; here we don 't need to fix k  consecutive element criteria. ; otherwise check for next possible element . ; 
def getLargestString(s, k):
    frequency_array = [0] * 26
    for i in range(len(s)):
        frequency_array[ord(s[i]) - ord('a')] += 1
    ans = ""
    i = 25
    while i >= 0:
        if (frequency_array[i] > k):
            temp = k
            st = chr(i + ord('a'))
            while (temp > 0):
                ans += st
                temp -= 1
            frequency_array[i] -= k
            j = i - 1
            while (frequency_array[j] <= 0 and j >= 0):
                j -= 1
            if (frequency_array[j] > 0 and j >= 0):
                str1 = chr(j + ord('a'))
                ans += str1
                frequency_array[j] -= 1
            else:
                break
        elif (frequency_array[i] > 0):
            temp = frequency_array[i]
            frequency_array[i] -= temp
            st = chr(i + ord('a'))
            while (temp > 0):
                ans += st
                temp -= 1
        else:
            i -= 1
    return ans


if __name__ == "__main__":
    S = "xxxxzza"
    k = 3
    print(getLargestString(S, k))

# Expected output:
zzxxxax
# minimum operations to make all elements equal using the second array | function to find the minimum operations required to make all elements of the array equal ; minimum element of a ; traverse through all final values ; variable indicating whether all elements can be converted to x or not ; total operations ; traverse through all array elements ; all elements can 't  be converted to x ; 
def minOperations(a, b, n):
    minA = min(a)
    for x in range(minA, -1, -1):
        check = True
        operations = 0
        for i in range(n):
            if (x % b[i] == a[i] % b[i]):
                operations += (a[i] - x) / b[i]
            else:
                check = False
                break
        if (check):
            return operations
    return -1


if __name__ == '__main__':
    N = 5
    A = [5, 7, 10, 5, 15]
    B = [2, 2, 1, 3, 5]
    print(int(minOperations(A, B, N)))

# Expected output:
8
# find the maximum sum ( a + b ) for a given input integer n satisfying the given condition | function to return the maximum sum of a + b satisfying the given condition ; initialize max_sum ; consider all the possible pairs ; check if the product is divisible by the sum ; storing the maximum sum in the max_sum variable ; return the max_sum value ; 
def getLargestSum(N):
    max_sum = 0
    for i in range(1, N + 1):
        for j in range(i + 1, N + 1, 1):
            if (i * j % (i + j) == 0):
                max_sum = max(max_sum, i + j)
    return max_sum


if __name__ == '__main__':
    N = 25
    max_sum = getLargestSum(N)
    print(max_sum)

# Expected output:
36
# maximize the sum of array after multiplying a prefix and suffix by | kadane 's algorithm to find the maximum subarray sum ; loop to find the maximum subarray array sum in the given array ; function to find the maximum sum of the array by multiplying the prefix and suffix by - 1 ; total intital sum ; loop to find the maximum sum of the array ; maximum value ; 
def maxSubArraySum(a, size):
    max_so_far = -10 ** 9
    max_ending_here = 0
    for i in range(size):
        max_ending_here = max_ending_here + a[i]
        if (max_ending_here < 0):
            max_ending_here = 0
        if (max_so_far < max_ending_here):
            max_so_far = max_ending_here
    return max_so_far


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


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

# Expected output:
6
# count of interesting primes upto n | python3 program to find the number of interesting primes up to n ; function to check if a number is prime or not ; if n is divisible by any number between 2 and sqrt ( n ) , it is not prime ; function to check if a number is perfect square or not ; find floating povalue of square root of x . ; if square root is an integer ; function to find the number of interesting primes less than equal to n . ; check whether the number is prime or not ; iterate for values of b ; check condition for a ; return the required answer ; 

import math


def isPrime(n):
    flag = 1
    i = 2
    while (i * i <= n):
        if (n % i == 0):
            flag = 0
            break
        i += 1
    return (True if flag == 1 else False)


def isPerfectSquare(x):
    sr = math .sqrt(x)
    return ((sr - math .floor(sr)) == 0)


def countInterestingPrimes(n):
    answer = 0
    for i in range(2, n):
        if (isPrime(i)):
            j = 1
            while (j * j * j * j <= i):
                if (isPerfectSquare(i - j * j * j * j)):
                    answer += 1
                    break
                j += 1
    return answer


if __name__ == '__main__':
    N = 10
    print(countInterestingPrimes(N))

# Expected output:
2
# maximize the number by flipping at most k bits | python implementation of the approach ; function to convert decimal number n to its binary representation stored as an array arr [ ] ; function to convert the number represented as a binary array arr [ ] into its decimal equivalent ; function to return the maximized number by flipping atmost k bits ; number of bits in n ; find the binary representation of n ; to count the number of 0 s flipped ; return the decimal equivalent of the maximized number ; 

import math


def decBinary(arr, n):
    k = int(math .log2(n))
    while (n > 0):
        arr[k] = n % 2
        k = k - 1
        n = n // 2


def binaryDec(arr, n):
    ans = 0
    for i in range(0, n):
        ans = ans + (arr[i] << (n - i - 1))
    return ans


def maxNum(n, k):
    l = int(math .log2(n)) + 1
    a = [0 for i in range(0, l)]
    decBinary(a, n)
    cn = 0
    for i in range(0, l):
        if (a[i] == 0 and cn < k):
            a[i] = 1
            cn = cn + 1
    return binaryDec(a, l)


n = 4
k = 1
print(maxNum(n, k))

# Expected output:
6
# find the subsequence with given sum in a superincreasing sequence | function to find the required subsequence ; current element cannot be a part of the required subsequence ; include current element in the required subsequence so update the sum ; print the elements of the required subsequence ; if the current element was included in the subsequence ; 
def findSubSeq(arr, n, sum):
    for i in range(n - 1, -1, -1):
        if (sum < arr[i]):
            arr[i] = -1
        else:
            sum -= arr[i]
    for i in range(n):
        if (arr[i] != -1):
            print(arr[i], end=" ")


if __name__ == "__main__":
    arr = [17, 25, 46, 94, 201, 400]
    n = len(arr)
    sum = 272
    findSubSeq(arr, n, sum)

# Expected output:
25 46 201
# find the most valued alphabet in the string | python implementation of the approach ; function to return the maximum valued alphabet ; set the first and the last occurrence of all the characters to - 1 ; update the occurrences of the characters ; only set the first occurrence if it hasn 't already been set ; to store the result ; for every alphabet ; if current alphabet doesn 't appear  in the given string ; if the current character has the highest value so far ; 

MAX = 26


def maxAlpha(str, len):
    first = [-1 for x in range(MAX)]
    last = [-1 for x in range(MAX)]
    for i in range(0, len):
        index = ord(str[i]) - 97
        if (first[index] == -1):
            first[index] = i
        last[index] = i
    ans = -1
    maxVal = -1
    for i in range(0, MAX):
        if (first[i] == -1):
            continue
        if ((last[i] - first[i]) > maxVal):
            maxVal = last[i] - first[i]
            ans = i
    return chr(ans + 97)


str = "abbba"
len = len(str)
print(maxAlpha(str, len))

# Expected output:
a
# queries for number of distinct elements from a given index till last index in an array | python implementation of the approach ; function to perform queries to find number of distinct elements from a given index till last index in an array ; check if current element already visited or not ; if not visited store current counter and increment it and mark check as 1 ; otherwise if visited simply store current counter ; perform queries ; 

MAX = 100001


def find_distinct(a, n, q, queries):
    check = [0] * MAX
    idx = [0] * MAX
    cnt = 1
    for i in range(n - 1, -1, -1):
        if (check[a[i]] == 0):
            idx[i] = cnt
            check[a[i]] = 1
            cnt += 1
        else:
            idx[i] = cnt - 1
    for i in range(0, q):
        m = queries[i]
        print(idx[m], end=" ")


a = [1, 2, 3, 1, 2, 3, 4, 5]
n = len(a)
queries = [0, 3, 5, 7]
q = len(queries)
find_distinct(a, n, q, queries)

# Expected output:
5 5 3 1