giulio98/xlcost-single-prompt huggingface dataset:
# minimum length subarray containing all unique elements after q operations | function to find minimum size subarray of all array elements ; updating the array after processing each query ; making it to 0 - indexing ; prefix sum array concept is used to obtain the count array ; iterating over the array to get the final array ; variable to get count of all unique elements ; hash to maintain perviously occurred elements ; loop to find the all unique elements ; array to maintain counter of encountered elements ; variable to store answer ; using two pointers approach ; increment counter if occurred once ; when all unique elements are found ; update answer with minimum size ; decrement count of elements from left ; decrement counter ; 
def subarrayLength(A, R, N, M):
    for i in range(M):
        l = R[i][0]
        r = R[i][1] + 1
        l -= 1
        r -= 1
        A[l] += 1
        if (r < N):
            A[r] -= 1
    for i in range(1, N):
        A[i] += A[i - 1]
    count = 0
    s = []
    for i in range(N):
        if (A[i]not in s):
            count += 1
        s .append(A[i])
    repeat = [0] * (count + 1)
    ans = N
    counter, left, right = 0, 0, 0
    while (right < N):
        cur_element = A[right]
        repeat[cur_element] += 1
        if (repeat[cur_element] == 1):
            counter += 1
        while (counter == count):
            ans = min(ans, right - left + 1)
            cur_element = A[left]
            repeat[cur_element] -= 1
            left += 1
            if (repeat[cur_element] == 0):
                counter -= 1
        right += 1
    return ans


if __name__ == "__main__":
    N, queries = 8, 6
    Q = [[1, 4], [3, 4], [4, 5], [5, 5], [7, 8], [8, 8]]
    A = [0] * N
    print(subarrayLength(A, Q, N, queries))

# Expected output:
4
# elements of array which can be expressed as power of prime numbers | function to mark all the exponent of prime numbers ; if number is prime then marking all of its exponent true ; function to display all required elements ; function to print the required numbers ; to find the largest number ; function call to mark all the exponential prime nos . ; function call ; 
def ModifiedSieveOfEratosthenes(N, Expo_Prime):
    primes = [True] * N
    for i in range(2, N):
        if (primes[i]):
            no = i
            while (no <= N):
                Expo_Prime[no] = True
                no *= i
            for j in range(i * i, N, i):
                primes[j] = False


def Display(arr, Expo_Prime, n):
    for i in range(n):
        if (Expo_Prime[arr[i]]):
            print(arr[i], end=" ")


def FindExpoPrime(arr, n):
    max = 0
    for i in range(n):
        if (max < arr[i]):
            max = arr[i]
    Expo_Prime = [False] * (max + 1)
    ModifiedSieveOfEratosthenes(max + 1, Expo_Prime)
    Display(arr, Expo_Prime, n)


if __name__ == "__main__":
    arr = [4, 6, 9, 16, 1, 3, 12, 36, 625, 1000]
    n = len(arr)
    FindExpoPrime(arr, n)

# Expected output:
4 9 16 3 625
# elements of array which can be expressed as power of some integer to given exponent k | method returns nth power of a ; smaller eps , denotes more accuracy ; initializing difference between two roots by int_max ; x ^ k denotes current value of x ; loop untiwe reach desired accuracy ; calculating current value from previous value by newton 's method ; function to check whether its k root is an integer or not ; function to find the numbers ; 
def nthRoot(A, N):
    xPre = 7
    eps = 1e-3
    delX = 10 ** 9
    xK = 0
    while (delX > eps):
        xK = ((N - 1.0) * xPre + A / pow(xPre, N - 1)) / N
        delX = abs(xK - xPre)
        xPre = xK
    return xK


def check(no, k):
    kth_root = nthRoot(no, k)
    num = int(kth_root)
    if (abs(num - kth_root) < 1e-4):
        return True
    return False


def printExpo(arr, n, k):
    for i in range(n):
        if (check(arr[i], k)):
            print(arr[i], end=" ")


if __name__ == '__main__':
    K = 6
    arr = [46656, 64, 256, 729, 16, 1000]
    n = len(arr)
    printExpo(arr, n, K)

# Expected output:
46656 64 729
# count of subsequences whose product is a difference of square of two integers | function to count the number of contiguous subsequences whose product can be expressed as square of difference of two integers ; iterating through the array ; check if that number can be expressed as the square of difference of two numbers ; variable to compute the product ; finding the remaining subsequences ; check if that number can be expressed as the square of difference of two numbers ; return the number of subsequences ; 
def CntcontSubs(a, n):
    c = 0
    d = 0
    sum = 1
    for i in range(n):
        if (a[i] % 2 != 0 or a[i] % 4 == 0):
            d += 1
        sum = a[i]
        for j in range(i + 1, n):
            sum = sum * a[j]
            if (sum % 2 != 0 or sum % 4 == 0):
                c += 1
        sum = 1
    return c + d


if __name__ == '__main__':
    arr = [5, 4, 2, 9, 8]
    n = len(arr)
    print(CntcontSubs(arr, n))

# Expected output:
13
# count of subsequences whose product is a difference of square of two integers | function to count all the contiguous subsequences whose product is expressed as the square of the difference of two integers ; creating vectors to store the remainders and the subsequences ; iterating through the array ; finding the remainder when the element is divided by 4 ; bringing all the elements in the range [ 0 , 3 ] ; if the remainder is 2 , store the index of the ; if the remainder is 2 , store the index of the ; finding the total number of subsequences ; if there are no numbers which yield the remainder 2 ; iterating through the vector ; if the element is 2 , find the nearest 2 or 0 and find the number of elements between them ; returning the count ; 
def CntcontSubs(a, n):
    prod = 1
    vect = []
    vect .append((0, 2))
    two, zero = [], []
    for i in range(n):
        a[i] = a[i] % 4
        if (a[i] < 0):
            a[i] = a[i] + 4
        if (a[i] == 2):
            two .append(i + 1)
        if (a[i] == 0):
            zero .append(i + 1)
        if (a[i] == 0 or a[i] == 2):
            vect .append((i + 1, a[i]))
    vect .append((n + 1, 2))
    total = (n * (n + 1)) // 2
    if (len(two) == 0):
        return total
    else:
        Sum = 0
        pos1, pos2, pos3 = -1, -1, -1
        sz = len(vect)
        for i in range(1, sz - 1):
            if (vect[i][1] == 2):
                Sum += ((vect[i][0] - vect[i - 1][0]) *
                        (vect[i + 1][0] - vect[i][0]) - 1)
        return (total - Sum - len(two))


a = [5, 4, 2, 9, 8]
n = len(a)
print(CntcontSubs(a, n))

# Expected output:
13
# program for finding the integral of a given function using boole 's rule | function to return the value of f ( x ) for the given value of x ; function to computes the integrand of y at the given intervals of x with step size h and the initial limit a and final limit b ; number of intervals ; computing the step size ; substituing a = 0 , b = 4 and h = 1 ; 
def y(x):
    return (1 / (1 + x))


def BooleRule(a, b):
    n = 4
    h = ((b - a) / n)
    sum = 0
    bl = (7 * y(a) + 32 * y(a + h) + 12 * y(a + 2 * h) +
          32 * y(a + 3 * h) + 7 * y(a + 4 * h)) * 2 * h / 45
    sum = sum + bl
    return sum


if __name__ == '__main__':
    lowlimit = 0
    upplimit = 4
    print("f(x) =", round(BooleRule(0, 4), 4))

# Expected output:
f(x) = 1.6178
# number of subsets with same and , or and xor values in an array | python3 program to find the number of subsets with equal bitwise and , or and xor values ; function to find the number of subsets with equal bitwise and , or and xor values ; precompute the modded powers of two for subset counting ; loop to iterate and find the modded powers of two for subset counting ; map to store the frequency of each element ; loop to compute the frequency ; for every element > 0 , the number of subsets formed using this element only is equal to 2 ^ ( frequency [ element ] - 1 ) . and for 0 , we have to find all the subsets , so 2 ^ ( frequency [ element ] ) - 1 ; if element is greater than 0 ; 

mod = 1000000007


def countSubsets(a, n):
    answer = 0
    powerOfTwo = [0 for x in range(100005)]
    powerOfTwo[0] = 1
    for i in range(1, 100005):
        powerOfTwo[i] = (powerOfTwo[i - 1] * 2) % mod
    frequency = {}
    for i in range(0, n):
        if a[i] in frequency:
            frequency[a[i]] += 1
        else:
            frequency[a[i]] = 1
    for key, value in frequency .items():
        if (key != 0):
            answer = (answer % mod + powerOfTwo[value - 1]) % mod
        else:
            answer = (answer % mod + powerOfTwo[value] - 1 + mod) % mod
    return answer


N = 6
A = [1, 3, 2, 1, 2, 1]
print(countSubsets(A, N))

# Expected output:
7
# Sum of all Perfect numbers lying in the range [ L , R ] | Python3 implementation to find the sum of all perfect numbers lying in the range [ L , R ] ; Array to store the sum ; Function to check if a number is a perfect number or not ; Iterating till the square root of the number and checking if the sum of divisors is equal to the number or not ; If it is a perfect number , then return the number ; Else , return 0 ; Function to precompute the sum of perfect squares and store then in an array

from math import sqrt
pref = [0] * 10000


def isPerfect(n):
    sum = 1
    for i in range(2, int(sqrt(n)) + 1):
        if (n % i == 0):
            if (i * i != n):
                sum = sum + i + n // i
            else:
                sum = sum + i
    if (sum == n and n != 1):
        return n
    return 0


def precomputation():
    for i in range(1, 10000):
        pref[i] = pref[i - 1] + isPerfect(i)


if __name__ == "__main__":
    L = 6
    R = 28
    precomputation()
    print(pref[R] - pref[L - 1])

# Expected output:
34
# ternary number system or base 3 numbers | python3 program to convert a ternary number to decimal number ; function to convert a ternary number to a decimal number ; if the number is greater than 0 , compute the decimal representation of the number ; loop to iterate through the number ; computing the decimal digit ; 

import math


def convertToDecimal(N):
    print("Decimal number of", N, "is:", end=" ")
    if (N != 0):
        decimalNumber = 0
        i = 0
        remainder = 0
        while (N != 0):
            remainder = N % 10
            N = N // 10
            decimalNumber += remainder * math .pow(3, i)
            i += 1
        print(decimalNumber)
    else:
        print("0")


Ternary = 10202202
convertToDecimal(Ternary)

# Expected output:
Decimal number of 10202202 is: 2747.0
# check if a given pair of numbers are betrothed numbers or not | python3 program for the above approach ; function to check whether n is perfect square or not ; find sqrt ; function to check whether the given pairs of numbers is betrothed numbers or not ; for finding the sum of all the divisors of first number n ; for finding the sum of all the divisors of second number m ; 

from math import sqrt, floor


def isPerfectSquare(N):
    sr = sqrt(N)
    return (sr - floor(sr)) == 0


def BetrothedNumbers(n, m):
    Sum1 = 1
    Sum2 = 1
    for i in range(2, int(sqrt(n)) + 1, 1):
        if (n % i == 0):
            if (isPerfectSquare(n)):
                Sum1 += i
            else:
                Sum1 += i + n / i
    for i in range(2, int(sqrt(m)) + 1, 1):
        if (m % i == 0):
            if (isPerfectSquare(m)):
                Sum2 += i
            else:
                Sum2 += i + (m / i)
    if ((n + 1 == Sum2) and (m + 1 == Sum1)):
        print("YES")
    else:
        print("NO")


if __name__ == '__main__':
    N = 9504
    M = 20734
    BetrothedNumbers(N, M)

# Expected output:
NO
# count of numbers upto m with gcd equals to k when paired with m | function to calculate gcd using euler totient function ; finding the prime factors of limit to calculate it 's  euler totient function ; calculating the euler totient function of ( mk ) ; function print the count of numbers whose gcd with m equals to k ; gcd of m with any integer cannot be equal to k ; 0 and m itself will be the only valid integers ; finding the number upto which coefficient of k can come ; 
def EulerTotientFunction(limit):
    copy = limit
    primes = []
    for i in range(2, limit + 1):
        if i * i > limit:
            break
        if (limit % i == 0):
            while (limit % i == 0):
                limit //= i
            primes .append(i)
    if (limit >= 2):
        primes .append(limit)
    ans = copy
    for it in primes:
        ans = (ans // it) * (it - 1)
    return ans


def CountGCD(m, k):
    if (m % k != 0):
        print(0)
        return
    if (m == k):
        print(2)
        return
    limit = m // k
    ans = EulerTotientFunction(limit)
    print(ans)


if __name__ == '__main__':
    M = 9
    K = 1
    CountGCD(M, K)

# Expected output:
6
# find the product of sum of two diagonals of a square matrix | function to find the product of the sum of diagonals . ; initialize sums of diagonals ; return the answer ; 
def product(mat, n):
    d1 = 0
    d2 = 0
    for i in range(n):
        d1 += mat[i][i]
        d2 += mat[i][n - i - 1]
    return d1 * d2


if __name__ == '__main__':
    mat = [[5, 8, 1], [5, 10, 3], [-6, 17, -9]]
    n = len(mat)
    print(product(mat, n))

# Expected output:
30
# program to calculate percentile of a student based on rank | program to calculate the percentile ; flat variable to store the result ; calculate and return the percentile ; 
def getPercentile(rank, students):
    result = (students - rank) / students * 100
    return result


if __name__ == "__main__":
    your_rank = 805
    total_students = 97481
    print(getPercentile(your_rank, total_students))

# Expected output:
99.17419804885054
# sum of numbers in the kth level of a fibonacci triangle | python3 implementation to find the sum of numbers in the kth level of a fibonacci triangle ; function to return the nth fibonacci number ; function to return the required sum of the array ; using our deduced result ; function to return the sum of fibonacci in the kth array ; count of fibonacci which are in the arrays from 1 to k - 1 ; 

import math
MAX = 1000000


def fib(n):
    phi = (1 + math .sqrt(5)) / 2
    return round(pow(phi, n) / math .sqrt(5))


def calculateSum(l, r):
    sum = fib(r + 2) - fib(l + 1)
    return sum


def sumFibonacci(k):
    l = (k * (k - 1)) / 2
    r = l + k
    sum = calculateSum(l, r - 1)
    return sum


k = 3
print(sumFibonacci(k))

# Expected output:
10
# print the sequence of size n in which every term is sum of previous k terms | function to generate the series in the form of array ; pick a starting point ; find the sum of all elements till count < k ; find the value of sum at i position ; 
def sumOfPrevK(N, K):
    arr = [0 for i in range(N)]
    arr[0] = 1
    for i in range(1, N):
        j = i - 1
        count = 0
        sum = 0
        while (j >= 0 and count < K):
            sum = sum + arr[j]
            j = j - 1
            count = count + 1
        arr[i] = sum
    for i in range(0, N):
        print(arr[i])


N = 10
K = 4
sumOfPrevK(N, K)

# Expected output:
1
1
2
4
8
15
29
56
108
208
# print the sequence of size n in which every term is sum of previous k terms | function to generate the series in the form of array ; pick a starting point ; computing the previous sum ; loop to print the series ; 
def sumOfPrevK(N, K):
    arr = [0] * N
    prevsum = 0
    arr[0] = 1
    for i in range(N - 1):
        if (i < K):
            arr[i + 1] = arr[i] + prevsum
            prevsum = arr[i + 1]
        else:
            arr[i + 1] = arr[i] + prevsum - arr[i + 1 - K]
            prevsum = arr[i + 1]
    for i in range(N):
        print(arr[i], end=" ")


if __name__ == '__main__':
    N = 8
    K = 3
    sumOfPrevK(N, K)

# Expected output:
1 1 2 4 7 12 20 33
# maximum gcd of all subarrays of length at least 2 | function to find gcd ; to store the maximum gcd ; traverse the array ; find gcd of the consecutive element ; if calculated gcd > maxgcd then update it ; print the maximum gcd ; 
def gcd(a, b):
    if (b == 0):
        return a
    return gcd(b, a % b)


def findMaxGCD(arr, n):
    maxGCD = 0
    for i in range(0, n - 1):
        val = gcd(arr[i], arr[i + 1])
        if (val > maxGCD):
            maxGCD = val
    print(maxGCD)


if __name__ == '__main__':
    arr = [3, 18, 9, 9, 5, 15, 8, 7, 6, 9]
    n = len(arr)
    findMaxGCD(arr, n)

# Expected output:
9
# sum of elements of an ap in the given range | function to find sum in the given range ; find the value of k ; find the common difference ; find the sum ; 
def findSum(arr, n, left, right):
    k = right - left
    d = arr[1] - arr[0]
    ans = arr[left - 1] * (k + 1)
    ans = ans + (d * (k * (k + 1))) // 2
    return ans


if __name__ == '__main__':
    arr = [2, 4, 6, 8, 10, 12, 14, 16]
    queries = 3
    q = [[2, 4], [2, 6], [5, 6]]
    n = len(arr)
    for i in range(queries):
        print(findSum(arr, n, q[i][0], q[i][1]))

# Expected output:
18
40
22
# check if a subarray exists with sum greater than the given array | function to check whether there exists a subarray whose sum is greater than or equal to sum of given array elements ; initialize sum with 0 ; checking possible prefix subarrays . if sum of them is less than or equal to zero , then return 1 ; again reset sum to zero ; checking possible suffix subarrays . if sum of them is less than or equal to zero , then return 1 ; otherwise return 0 ; 
def subarrayPossible(arr, n):
    sum = 0
    for i in range(n):
        sum += arr[i]
        if (sum <= 0):
            return True
    sum = 0
    for i in range(n - 1, -1, -1):
        sum += arr[i]
        if (sum <= 0):
            return True
    return False


if __name__ == '__main__':
    arr = [10, 5, -12, 7, -10, 20, 30, -10, 50, 60]
    size = len(arr)
    if (subarrayPossible(arr, size)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# finding integreand using weedle 's rule | a sample function f ( x ) = 1 / ( 1 + x ^ 2 ) ; function to find the integral value of f ( x ) with step size h , with initial lower limit and upper limit a and b ; find step size h ; to store the final sum ; find sum using weedle 's formula ; return the final sum ; 
def y(x):
    num = 1
    denom = float(1.0 + x * x)
    return num / denom


def WeedleRule(a, b):
    h = (b - a) / 6
    sum = 0
    sum = sum + (((3 * h) / 10) * (y(a) + y(a + 2 * h) + 5 * y(a + h) +
                 6 * y(a + 3 * h) + y(a + 4 * h) + 5 * y(a + 5 * h) + y(a + 6 * h)))
    return sum


if __name__ == '__main__':
    a = 0
    b = 6
    num = WeedleRule(a, b)
    print("f(x) = {0:.6f}".format(num))

# Expected output:
f(x) = 1.373447
# find the minimum number to be added to n to make it a prime number | function to check if a given number is a prime or not ; base cases ; this is checked so that we can skip middle five numbers in below loop ; for all the remaining numbers , check if any number is a factor if the number or not ; if none of the above numbers are the factors for the number , then the given number is prime ; function to return the smallest number to be added to make a number prime ; base case ; loop continuously until isprime returns true for a number greater than n ; if the number is not a prime , then increment the number by 1 and the counter which stores the number to be added ; 
def isPrime(n):
    if (n <= 1):
        return False
    if (n <= 3):
        return True
    if (n % 2 == 0 or n % 3 == 0):
        return False
    i = 5
    while (i * i <= n):
        if (n % i == 0 or n % (i + 2) == 0):
            return False
        i += 6
    return True


def findSmallest(N):
    if (N == 0):
        return 2
    if (N == 1):
        return 1
    prime, counter = N, 0
    found = False
    while (not found):
        if (isPrime(prime)):
            found = True
        else:
            prime += 1
            counter += 1
    return counter


if __name__ == "__main__":
    N = 10
    print(findSmallest(N))

# Expected output:
1
# find the position of the given prime number | python3 program to find the position of the given prime number ; function to precompute the position of every prime number using sieve ; 0 and 1 are not prime numbers ; variable to store the position ; incrementing the position for every prime number ; 

limit = 1000000
position = [0] * (limit + 1)


def sieve():
    position[0] = -1
    position[1] = -1
    pos = 0
    for i in range(2, limit + 1):
        if (position[i] == 0):
            pos += 1
            position[i] = pos
            for j in range(i * 2, limit + 1, i):
                position[j] = -1


if __name__ == "__main__":
    sieve()
    n = 11
    print(position[n])

# Expected output:
5
# minimum possible sum of array elements after performing the given operation | function to find the maximum sum of the sub array ; max_so_far represents the maximum sum found till now and max_ending_here represents the maximum sum ending at a specific index ; iterating through the array to find the maximum sum of the subarray ; if the maximum sum ending at a specific index becomes less than 0 , then making it equal to 0. ; function to find the minimum possible sum of the array elements after performing the given operation ; finding the sum of the array ; computing the minimum sum of the array ; 
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_so_far < max_ending_here):
            max_so_far = max_ending_here
        if (max_ending_here < 0):
            max_ending_here = 0
    return max_so_far


def minPossibleSum(a, n, x):
    mxSum = maxSubArraySum(a, n)
    sum = 0
    for i in range(n):
        sum += a[i]
    sum = sum - mxSum + mxSum / x
    print(round(sum, 2))


if __name__ == '__main__':
    N = 3
    X = 2
    A = [1, -2, 3]
    minPossibleSum(A, N, X)

# Expected output:
0.5
# print the two possible permutations from a given sequence | function to check if the sequence is concatenation of two permutations or not ; computing the sum of all the elements in the array ; computing the prefix sum for all the elements in the array ; iterating through the i from lengths 1 to n - 1 ; sum of first i + 1 elements ; sum of remaining n - i - 1 elements ; lengths of the 2 permutations ; checking if the sums satisfy the formula or not ; function to print the two permutations ; print the first permutation ; print the second permutation ; function to find the two permutations from the given sequence ; if the sequence is not a concatenation of two permutations ; find the largest element in the array and set the lengths of the permutations accordingly ; 
def checkPermutation(arr, n):
    sum = 0
    for i in range(n):
        sum += arr[i]
    prefix = [0 for i in range(n + 1)]
    prefix[0] = arr[0]
    for i in range(1, n):
        prefix[i] = prefix[i - 1] + arr[i]
    for i in range(n - 1):
        lsum = prefix[i]
        rsum = sum - prefix[i]
        l_len = i + 1
        r_len = n - i - 1
        if (((2 * lsum) == (l_len * (l_len + 1)))
                and ((2 * rsum) == (r_len * (r_len + 1)))):
            return True
    return False


def printPermutations(arr, n, l1, l2):
    for i in range(l1):
        print(arr[i], end=" ")
    print("", end="")
    for i in range(l1, n, 1):
        print(arr[i], end=" ")


def findPermutations(arr, n):
    if (checkPermutation(arr, n) == False):
        print("Not Possible")
        return
    l1 = 0
    l2 = 0
    l1 = max(arr)
    l2 = n - l1
    s1 = set()
    s2 = set()
    for i in range(l1):
        s1 .add(arr[i])
    for i in range(l1, n):
        s2 .add(arr[i])
    if (len(s1) == l1 and len(s2) == l2):
        printPermutations(arr, n, l1, l2)
    else:
        temp = l1
        l1 = l2
        l2 = temp
        printPermutations(arr, n, l1, l2)


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

# Expected output:
2 1 3 4 5 6 7 8 9 1 10 2