giulio98/xlcost-single-prompt huggingface dataset:
# probability such that two subset contains same number of elements | python3 implementation of the above approach ; returns value of binomial coefficient c ( n , k ) ; since c ( n , k ) = c ( n , n - k ) ; calculate value of ; iterative function to calculate ( x ^ y ) in o ( log y ) ; initialize result ; if y is odd , multiply x with result ; y must be even now y = y / 2 ; change x to x ^ 2 ; function to find probability ; calculate total possible ways and favourable ways . ; divide by gcd such that they become relatively coprime ; 

import math


def binomialCoeff(n, k):
    res = 1
    if (k > n - k):
        k = n - k
    for i in range(0, k):
        res = res * (n - i)
        res = res // (i + 1)
    return res


def power(x, y):
    res = 1
    while (y > 0):
        if (y & 1):
            res = res * x
        y = y // 2
        x = x * x
    return res


def FindProbability(n):
    up = binomialCoeff(2 * n, n)
    down = power(2, 2 * n)
    g = math .gcd(up, down)
    up = up // g
    down = down // g
    print(up, "/", down)


N = 8
FindProbability(N)

# Expected output:
6435 / 32768
# largest perfect square number in an array | python3 program to find the largest perfect square number among n numbers ; function to check if a number is perfect square number or not ; takes the sqrt of the number ; checks if it is a perfect square number ; function to find the largest perfect square number in the array ; stores the maximum of all perfect square numbers ; traverse all elements in the array ; store the maximum if current element is a perfect square ; 

from math import sqrt


def checkPerfectSquare(n):
    d = sqrt(n)
    if d * d == n:
        return True
    return False


def largestPerfectSquareNumber(a, n):
    maxi = -1
    for i in range(n):
        if (checkPerfectSquare(a[i])):
            maxi = max(a[i], maxi)
    return maxi


if __name__ == "__main__":
    a = [16, 20, 25, 2, 3, 10]
    n = len(a)
    print(largestPerfectSquareNumber(a, n))

# Expected output:
25
# maximum number of parallelograms that can be made using the given length of line segments | function to find the maximum number of parallelograms can be made ; finding the length of the frequency array ; increasing the occurrence of each segment ; to store the count of parallelograms ; counting parallelograms that can be made using 4 similar sides ; counting segments which have occurrence left >= 2 ; adding parallelograms that can be made using 2 similar sides ; 
def convert(n, a):
    z = max(a) + 1
    ff = [0] * z
    for i in range(n):
        ff[a[i]] += 1
    cc = 0
    for i in range(z):
        cc += ff[i] // 4
        ff[i] = ff[i] % 4
    vv = 0
    for i in range(z):
        if (ff[i] >= 2):
            vv += 1
    cc += vv // 2
    print(cc)


n = 4
a = [1, 2, 1, 2]
convert(n, a)

# Expected output:
1
# count pairs ( i , j ) such that ( i + j ) is divisible by a and b both | python3 implementation of above approach ; function to find the lcm ; function to count the pairs ; 

from math import gcd


def find_LCM(x, y):
    return (x * y) // gcd(x, y)


def CountPairs(n, m, A, B):
    cnt = 0
    lcm = find_LCM(A, B)
    for i in range(1, n + 1):
        cnt += (m + (i % lcm)) // lcm
    return cnt


if __name__ == "__main__":
    n, m, A, B = 60, 90, 5, 10
    print(CountPairs(n, m, A, B))

# Expected output:
540
# sorting without comparison of elements | represents node of a doubly linked list ; count of elements in given range ; count frequencies of all elements ; traverse through range . for every element , print it its count times . ; 
def sortArr(arr, n, min_no, max_no):
    m = max_no - min_no + 1
    c = [0] * m
    for i in range(n):
        c[arr[i] - min_no] += 1
    for i in range(m):
        for j in range((c[i])):
            print((i + min_no), end=" ")


arr = [10, 10, 1, 4, 4, 100, 0]
min_no, max_no = 0, 100
n = len(arr)
sortArr(arr, n, min_no, max_no)

# Expected output:
0 1 4 4 10 10 100
# find binary permutations of given size not present in the array | python 3 program for the above approach ; function to find a binary string of same length other than the strings present in the array ; map all the strings present in the array ; find all the substring that can be made ; if num already exists then increase counter ; if not found print ; if all the substrings are present then print - 1 ; 

from math import pow


def findMissingBinaryString(nums, N):
    s = set()
    counter = 0
    for x in nums:
        s .add(x)
    total = int(pow(2, N))
    ans = ""
    for i in range(total):
        num = ""
        j = N - 1
        while (j >= 0):
            if (i & (1 << j)):
                num += '1'
            else:
                num += '0'
            j -= 1
        if (num in s):
            continue
            counter += 1
        else:
            print(num, end=", ")
    if (counter == total):
        print("-1")


if __name__ == '__main__':
    N = 3
    arr = ["101", "111", "001", "011", "100", "110"]
    findMissingBinaryString(arr, N)

# Expected output:
000, 010,
# queries to find number of connected grid components of given sizes in a matrix | python 3 implementation for the above approach ; stores information about which cell are already visited in a particular bfs ; stores the final result grid ; stores the count of cells in the largest connected component ; function checks if a cell is valid , i . e . it is inside the grid and equal to 1 ; map to count the frequency of each connected component ; function to calculate the largest connected component ; iterate over every cell ; stores the indices of the matrix cells ; mark the starting cell as visited and push it into the queue ; iterate while the queue is not empty ; go to the adjacent cells ; 

n = 6
m = 6
dx = [0, 1, -1, 0]
dy = [1, 0, 0, -1]
visited = [[False for i in range(m)]for j in range(n)]
result = [[0 for i in range(m)]for j in range(n)]
COUNT = 0


def is_valid(x, y, matrix):
    if (x < n and y < m and x >= 0 and y >= 0):
        if (visited[x][y] == False and matrix[x][y] == 1):
            return True
        else:
            return False
    else:
        return False


mp = {}


def findComponentSize(matrix):
    for i in range(n):
        for j in range(m):
            if (visited[i][j] == False and matrix[i][j] == 1):
                COUNT = 0
                q = []
                q .append([i, j])
                visited[i][j] = True
                while (len(q) != 0):
                    p = q[0]
                    q = q[1:]
                    x = p[0]
                    y = p[1]
                    COUNT += 1
                    for i in range(4):
                        newX = x + dx[i]
                        newY = y + dy[i]
                        if (is_valid(newX, newY, matrix)):
                            q .append([newX, newY])
                            visited[newX][newY] = True
                if COUNT in mp:
                    mp[COUNT] += 1
                else:
                    mp[COUNT] = 1


if __name__ == '__main__':
    matrix = [[1, 1, 1, 1, 1, 1], [1, 1, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1], [
        0, 0, 0, 1, 1, 1], [0, 0, 1, 0, 0, 0], [1, 0, 0, 0, 0, 0]]
    queries = [6, 1, 8, 2]
    N = len(queries)
    findComponentSize(matrix)
    for i in range(N):
        if queries[i] in mp:
            print(mp[queries[i]], end=" ")
        else:
            print(0, end=" ")

# Expected output:
1 2 1 0
# minimum value of x such that sum of arr [ i ] | function to check if there exists an x that satisfies the given conditions ; find the required value of the given expression ; function to find the minimum value of x using binary search . ; boundaries of the binary search ; find the middle value ; check for the middle value ; update the upper ; update the lower ; 
def check(a, b, k, n, x):
    sum = 0
    for i in range(n):
        sum = sum + pow(max(a[i] - x, 0), b[i])
    if (sum <= k):
        return True
    else:
        return False


def findMin(a, b, n, k):
    l = 0
    u = max(a)
    while (l < u):
        m = (l + u) // 2
        if (check(a, b, k, n, m)):
            u = m
        else:
            l = m + 1
    return l


if __name__ == '__main__':
    arr = [2, 1, 4, 3, 5]
    brr = [4, 3, 2, 3, 1]
    K = 12
    N = len(arr)
    print(findMin(arr, brr, N, K))

# Expected output:
2
# count of indices pairs such that product of elements at these indices is equal to absolute difference of indices | function to count the number of pairs ( i , j ) such that arr [ i ] * arr [ j ] is equal to abs ( i - j ) ; stores the resultant number of pairs ; iterate over the range [ 0 , n ) ; now , iterate from the value arr [ i ] - ( i % arr [ i ] ) till n with an increment of arr [ i ] ; if the given criteria satisfy then increment the value of count ; return the resultant count ; 
def getPairsCount(arr, n):
    count = 0
    for i in range(0, n):
        s = arr[i] - (i % arr[i])
        for j in range(s, n):
            if (i < j and (arr[i] * arr[j]) == abs(i - j)):
                count += 1
    return count


arr = [1, 1, 2, 4]
N = len(arr)
print(getPairsCount(arr, N))

# Expected output:
2
# find frequency of each character with positions in given array of strings | function to print every occurence of every characters in every string ; iterate over the vector arr [ ] ; traverse the string arr [ i ] ; push the pair of { i + 1 , j + 1 } in mp [ arr [ i ] [ j ] ] ; print the occurences of every character ; 
def printOccurences(arr, N):
    mp = [[]for i in range(26)]
    for i in range(N):
        for j in range(len(arr[i])):
            mp[ord(arr[i][j]) - ord('a')].append((i + 1, j + 1))
    for i in range(26):
        if len(mp[i]) == 0:
            continue
        print("Occurences of:", chr(i + ord('a')), "=", end=" ")
        for j in mp[i]:
            print("[" + str(j[0]) + " " + str(j[1]) + "] ", end="")
        print()


if __name__ == '__main__':
    arr = ["geeksforgeeks", "gfg"]
    N = len(arr)
    printOccurences(arr, N)

# Expected output:
Occurences of: e = [1 2] [1 3] [1 10] [1 11] 
Occurences of: f = [1 6] [2 2] 
Occurences of: g = [1 1] [1 9] [2 1] [2 3] 
Occurences of: k = [1 4] [1 12] 
Occurences of: o = [1 7] 
Occurences of: r = [1 8] 
Occurences of: s = [1 5] [1 13]
# count of subarrays with x as the most frequent element , for each value of x from 1 to n | function to calculate the number of subarrays where x ( 1 <= x <= n ) is the most frequent element ; array to store the final answers ; array to store current frequencies ; variable to store the current most frequent element ; update frequency array ; update answer ; pranswer ; 
def mostFrequent(arr, N):
    ans = [0] * N
    for i in range(N):
        count = [0] * N
        best = 0
        for j in range(i, N):
            count[arr[j] - 1] += 1
            if (count[arr[j] - 1] > count[best - 1]
                    or (count[arr[j] - 1] == count[best - 1] and arr[j] < best)):
                best = arr[j]
            ans[best - 1] += 1
    print(*ans)


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

# Expected output:
4 5 1 0
# count array elements whose highest power of 2 less than or equal to that number is present in the given array | python program for the above approach ; function to count array elements whose highest power of 2 is less than or equal to that number is present in the given array ; stores the resultant count of array elements ; stores frequency of visited array elements ; traverse the array ; calculate log base 2 of the element arr [ i ] ; highest power of 2 whose value is at most arr [ i ] ; increment the count by 1 ; return the resultant count ; 

from math import log2


def countElement(arr, N):
    count = 0
    m = {}
    for i in range(N):
        m[arr[i]] = m .get(arr[i], 0) + 1
    for i in range(N):
        lg = int(log2(arr[i]))
        p = pow(2, lg)
        if (p in m):
            count += 1
    return count


if __name__ == '__main__':
    arr = [3, 4, 6, 9]
    N = len(arr)
    print(countElement(arr, N))

# Expected output:
2
# maximum number of intersections possible for any of the n given segments | python 3 program for the above approach ; function to find the maximum number of intersections one segment has with all the other given segments ; stores the resultant maximum count ; stores the starting and the ending points ; sort arrays points in the ascending order ; traverse the array arr [ ] ; find the count of segments on left of ith segment ; find the count of segments on right of ith segment ; find the total segments not intersecting with the current segment ; store the count of segments that intersect with the ith segment ; update the value of count ; return the resultant count ; 

from bisect import bisect_left, bisect_right


def lower_bound(a, low, high, element):
    while (low < high):
        middle = low + (high - low) // 2
        if (element > a[middle]):
            low = middle + 1
        else:
            high = middle
    return low


def maximumIntersections(arr, N):
    count = 0
    L = [0] * N
    R = [0] * N
    for i in range(N):
        L[i] = arr[i][0]
        R[i] = arr[i][1]
    L .sort()
    R .sort()
    for i in range(N):
        l = arr[i][0]
        r = arr[i][1]
        x = lower_bound(L, 0, N, l)
        y = N - lower_bound(R, 0, N, r + 1)
        cnt = x + y
        cnt = N - cnt - 1
        count = max(count, cnt)
    return count


if __name__ == "__main__":
    arr = [[1, 6], [5, 5], [2, 3]]
    N = len(arr)
    print(maximumIntersections(arr, N))

# Expected output:
2
# program to find the nth composite number | function to find the nth composite numbers using sieve of eratosthenes ; sieve of prime numbers ;  ; iterate over the range [ 2 , 1000005 ] ; if isprime [ p ] is true ; iterate over the range [ p * p , 1000005 ] ; stores the list of composite numbers ; iterate over the range [ 4 , 1000005 ] ; if i is not prime ; return nth composite number ; 
def NthComposite(N):
    IsPrime = [True] * 1000005
    for p in range(2, 1000005):
        if p * p > 1000005:
            break
        if (IsPrime[p]):
            for i in range(p * p, 1000005, p):
                IsPrime[i] = False
    Composites = []
    for p in range(4, 1000005):
        if (not IsPrime[p]):
            Composites .append(p)
    return Composites[N - 1]


if __name__ == '__main__':
    N = 4
    print(NthComposite(N))

# Expected output:
9
# modify array of strings by replacing characters repeating in the same or remaining strings | function to remove duplicate characters across the strings ; stores distinct characters ; size of the array ; stores the list of modified strings ; traverse the array ; stores the modified string ; iterate over the characters of the modified string ; if character is already present ; insert character into the set ; print the list of modified strings ; print each string ; 
def removeDuplicateCharacters(arr):
    cset = set([])
    n = len(arr)
    out = []
    for st in arr:
        out_curr = ""
        for ch in st:
            if (ch in cset):
                continue
            out_curr += ch
            cset .add(ch)
        if (len(out_curr)):
            out .append(out_curr)
    for i in range(len(out)):
        print(out[i], end=" ")


if __name__ == "__main__":
    arr = ["Geeks", "For", "Geeks", "Post"]
    removeDuplicateCharacters(arr)

# Expected output:
Geks For Pt
# sum of array elements which are prime factors of a given number | function to check if a number is prime or not ; corner cases ; check if n is a multiple of 2 or 3 ; above condition allows to check only for every 6 th number , starting from 5 ; if n is a multiple of i and i + 2 ; function to find the sum of array elements which are prime factors of k ; stores the required sum ; traverse the given array ; if current element is a prime factor of k , add it to the sum ; print the result ; 
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 = i + 6
    return True


def primeFactorSum(arr, n, k):
    sum = 0
    for i in range(n):
        if (k % arr[i] == 0 and isPrime(arr[i])):
            sum = sum + arr[i]
    print(sum)


arr = [1, 2, 3, 5, 6, 7, 15]
N = len(arr)
K = 35
primeFactorSum(arr, N, K)

# Expected output:
12
# minimum number of array elements from either ends required to be subtracted from x to reduce x to 0 | python3 program to implement the above approach ; function to count the minimum number of operations required to reduce x to 0 ; if sum of the array is less than x ; stores the count of operations ; two pointers to traverse the array ; reduce x by the sum of the entire array ; iterate until l reaches the front of the array ; if sum of elements from the front exceeds x ; shift towards left ; if sum exceeds 0 ; reduce x by elements from the right ; if x is reduced to 0 ; update the minimum count of operations required ; 

import math


def minOperations(nums, x):
    if sum(nums) < x:
        return -1
    ans = math .inf
    l, r = len(nums) - 1, len(nums)
    x -= sum(nums)
    while l >= 0:
        if x <= 0:
            x += nums[l]
            l -= 1
        if x > 0:
            r -= 1
            x -= nums[r]
        if x == 0:
            ans = min(ans, (l + 1) + (len(nums) - r))
    return ans if ans < math .inf else -1


nums = [1, 1, 4, 2, 3]
x = 5
print(minOperations(nums, x))

# Expected output:
2
# number of subarrays having even product | function to count subarrays with even product ; total number of subarrays ; counter variables ; traverse the array ; if current element is odd ; update count of subarrays with odd product up to index i ; print count of subarrays with even product ; 
def evenproduct(arr, length):
    total_subarray = length * (length + 1) // 2
    total_odd = 0
    count_odd = 0
    for i in range(length):
        if (arr[i] % 2 == 0):
            count_odd = 0
        else:
            count_odd += 1
            total_odd += count_odd
    print(total_subarray - total_odd)


if __name__ == "__main__":
    arr = [7, 5, 4, 9]
    length = len(arr)
    evenproduct(arr, length)

# Expected output:
6
# check if all rows of a binary matrix have all ones placed adjacently or not | function to check if all 1 s are placed adjacently in an array or not ; base case ; stores the sum of xor of all pair of adjacent elements ; calculate sum of xor of all pair of adjacent elements ; check for corner cases ; return true ; function to check if all the rows have all 1 s grouped together or not ; traverse each row ; check if all 1 s are placed together in the ith row or not ; function to check if all 1 s in a row are grouped together in a matrix or not ; print the result ; 
def checkGroup(arr):
    if len(arr) <= 2:
        return True
    corner = arr[0] + arr[-1]
    xorSum = 0
    for i in range(len(arr) - 1):
        xorSum += (arr[i] ^ arr[i + 1])
    if not corner:
        if xorSum > 2:
            return False
    elif corner == 1:
        if xorSum > 1:
            return False
    else:
        if xorSum > 0:
            return False
    return True


def isInGroupUtil(mat):
    for i in mat:
        if not checkGroup(i):
            return False
    return True


def isInGroup(mat):
    ans = isInGroupUtil(mat)
    if ans:
        print("Yes")
    else:
        print("No")


mat = [[0, 1, 1, 0], [1, 1, 0, 0], [0, 0, 0, 1], [1, 1, 1, 0]]
isInGroup(mat)

# Expected output:
Yes
# print all numbers up to n having product of digits equal to k | function to find the product of digits of a number ; stores the product of digits of a number ; return the product ; function to print all numbers upto n having product of digits equal to k ; stores whether any number satisfying the given conditions exists or not ; iterate over the range [ 1 , n ] ; if product of digits of arr [ i ] is equal to k or not ; print that number ; if no numbers are found ; 
def productOfDigits(N):
    product = 1
    while (N != 0):
        product = product * (N % 10)
        N = N // 10
    return product


def productOfDigitsK(N, K):
    flag = 0
    for i in range(1, N + 1):
        if (K == productOfDigits(i)):
            print(i, end=" ")
            flag = 1
    if (flag == 0):
        print("-1")


if __name__ == "__main__":
    N = 500
    K = 10
    productOfDigitsK(N, K)

# Expected output:
25 52 125 152 215 251
# minimize difference between maximum and minimum array elements by removing a k | function to minimize difference between maximum and minimum array elements by removing a k - length subarray ; size of array ; stores the maximum and minimum in the suffix subarray [ i . . n - 1 ] ; traverse the array ; stores the maximum and minimum in the prefix subarray [ 0 . . i - 1 ] ; store the minimum difference ; traverse the array ; if the suffix doesn 't exceed  the end of the array ; store the maximum element in array after removing subarray of size k ; stores the maximum element in array after removing subarray of size k ; update minimum difference ; updating the maxprefix and minprefix with current element ; print the minimum difference ; 
def minimiseDifference(arr, K):
    N = len(arr)
    maxSuffix = [0 for i in range(N + 1)]
    minSuffix = [0 for i in range(N + 1)]
    maxSuffix[N] = -1e9
    minSuffix[N] = 1e9
    maxSuffix[N - 1] = arr[N - 1]
    minSuffix[N - 1] = arr[N - 1]
    i = N - 2
    while (i >= 0):
        maxSuffix[i] = max(maxSuffix[i + 1], arr[i])
        minSuffix[i] = min(minSuffix[i + 1], arr[i])
        i -= 1
    maxPrefix = arr[0]
    minPrefix = arr[0]
    minDiff = maxSuffix[K] - minSuffix[K]
    for i in range(1, N):
        if (i + K <= N):
            maximum = max(maxSuffix[i + K], maxPrefix)
            minimum = min(minSuffix[i + K], minPrefix)
            minDiff = min(minDiff, maximum - minimum)
        maxPrefix = max(maxPrefix, arr[i])
        minPrefix = min(minPrefix, arr[i])
    print(minDiff)


if __name__ == '__main__':
    arr = [4, 5, 8, 9, 1, 2]
    K = 2
    minimiseDifference(arr, K)

# Expected output:
4
# minimize segments required to be removed such that at least one segment intersects with all remaining segments | pyhton3 program for the above approach ; function to find the minimum number of segments required to be deleted ; stores the start and end points ; traverse segments and fill the startpoints and endpoints ; sort the startpoints ; sort the startpoints ; store the minimum number of deletions required and initialize with ( n - 1 ) ; traverse the array segments [ ] ; store the starting point ; store the ending point ; store the number of segments satisfying the first condition of non - intersection ; store the number of segments satisfying the second condition of non - intersection ; update answer ; print the answer ; 

from bisect import bisect_left, bisect_right


def minSegments(segments, n):
    startPoints = [0 for i in range(n)]
    endPoints = [0 for i in range(n)]
    for i in range(n):
        startPoints[i] = segments[i][0]
        endPoints[i] = segments[i][1]
    startPoints .sort(reverse=False)
    endPoints .sort(reverse=False)
    ans = n - 1
    for i in range(n):
        f = segments[i][0]
        s = segments[i][1]
        leftDelete = bisect_left(endPoints, f)
        rightDelete = max(0, n - bisect_right(startPoints, s))
        ans = min(ans, leftDelete + rightDelete)
    print(ans)


if __name__ == '__main__':
    arr = [[1, 2], [5, 6], [6, 7], [7, 10], [8, 9]]
    N = len(arr)
    minSegments(arr, N)

# Expected output:
2