giulio98/xlcost-single-prompt huggingface dataset:
# sgn value of a polynomial | returns value of poly [ 0 ] x ( n - 1 ) + poly [ 1 ] x ( n - 2 ) + . . + poly [ n - 1 ] ; 
def horner(poly, n, x):
    result = poly[0]
    for i in range(1, n):
        result = (result * x + poly[i])
    return result


def findSign(poly, n, x):
    result = horner(poly, n, x)
    if (result > 0):
        return 1
    elif (result < 0):
        return -1
    return 0


poly = [2, -6, 2, -1]
x = 3
n = len(poly)
print("Sign of polynomial is ", findSign(poly, n, x))

# Expected output:
Sign of polynomial is  1
# insert minimum number in array so that sum of array becomes prime | python3 program to find minimum number to insert in array so their sum is prime ; function to calculate prime using sieve of eratosthenes ; find prime number greater than a number ; find prime greater than n ; check if num is prime ; increment num ; to find number to be added so sum of array is prime ; call sieveoferatostheneses to calculate primes ; to find sum of array elements ; if sum is already prime return 0 ; to find prime number greater than sum ; return difference of sum and num ; 

isPrime = [1] * 100005


def sieveOfEratostheneses():
    isPrime[1] = False
    i = 2
    while i * i < 100005:
        if (isPrime[i]):
            j = 2 * i
            while j < 100005:
                isPrime[j] = False
                j += i
        i += 1
    return


def findPrime(n):
    num = n + 1
    while (num):
        if isPrime[num]:
            return num
        num += 1
    return 0


def minNumber(arr):
    sieveOfEratostheneses()
    s = 0
    for i in range(0, len(arr)):
        s += arr[i]
    if isPrime[s]:
        return 0
    num = findPrime(s)
    return num - s


arr = [2, 4, 6, 8, 12]
print(minNumber(arr))

# Expected output:
5
# sum of all subarrays | set 1 | computes sum all sub - array ; pick starting point ; pick ending point ; sum subarray between current starting and ending points ; 
def SubArraySum(arr, n):
    temp, result = 0, 0
    for i in range(0, n):
        temp = 0
        for j in range(i, n):
            temp += arr[j]
            result += temp
    return result


arr = [1, 2, 3]
n = len(arr)
print("Sum of SubArray :", SubArraySum(arr, n))

# Expected output:
Sum of SubArray : 20
# highest power of 2 less than or equal to given number | python3 program to find highest power of 2 smaller than or equal to n . ; 

import math


def highestPowerof2(n):
    p = int(math .log(n, 2))
    return int(pow(2, p))


n = 10
print(highestPowerof2(n))

# Expected output:
8
# find ( a ^ b ) % m where ' a ' is very large | python program to find ( a ^ b ) mod m for a large 'a ; utility function to calculate a % m ; convert string s [ i ] to integer which gives the digit value and form the number ; returns find ( a ^ b ) % m ; find a % m ; now multiply ans by b - 1 times and take mod with m ; 
def aModM(s, mod):
    number = 0
    for i in range(len(s)):
        number = (number * 10 + int(s[i]))
        number = number % m
    return number


def ApowBmodM(a, b, m):
    ans = aModM(a, m)
    mul = ans
    for i in range(1, b):
        ans = (ans * mul) % m
    return ans


a = "987584345091051645734583954832576"
b, m = 3, 11
print(ApowBmodM(a, b, m))

# Expected output:
10
# lagrange 's interpolation | to represent a data point corresponding to x and y = f ( x ) ; function to interpolate the given data points using lagrange 's formula xi -> corresponds to the new data point whose value is to be obtained n -> represents the number of known data points ; initialize result ; compute individual terms of above formula ; add current term to result ; 

class Data:
    def __init__(self, x, y):
        self .x = x
        self .y = y


def interpolate(f: list, xi: int, n: int) -> float:
    result = 0.0
    for i in range(n):
        term = f[i].y
        for j in range(n):
            if j != i:
                term = term * (xi - f[j].x) / (f[i].x - f[j].x)
        result += term
    return result


if __name__ == "__main__":
    f = [Data(0, 2), Data(1, 3), Data(2, 12), Data(5, 147)]
    print("Value of f(3) is :", interpolate(f, 3, 4))

# Expected output:
Value of f(3) is : 35.0
# sieve of sundaram to print all primes smaller than n | prints all prime numbers smaller ; in general sieve of sundaram , produces primes smaller than ( 2 * x + 2 ) for a number given number x . since we want primes smaller than n , we reduce n to half ; this array is used to separate numbers of the form i + j + 2 ij from others where 1 <= i <= j initialize all elements as not marked ; main logic of sundaram . mark all numbers of the form i + j + 2 ij as true where 1 <= i <= j ; since 2 is a prime number ; print other primes . remaining primes are of the form 2 * i + 1 such that marked [ i ] is false . ; 
def SieveOfSundaram(n):
    nNew = int((n - 1) / 2)
    marked = [0] * (nNew + 1)
    for i in range(1, nNew + 1):
        j = i
        while ((i + j + 2 * i * j) <= nNew):
            marked[i + j + 2 * i * j] = 1
            j += 1
    if (n > 2):
        print(2, end=" ")
    for i in range(1, nNew + 1):
        if (marked[i] == 0):
            print((2 * i + 1), end=" ")


n = 20
SieveOfSundaram(n)

# Expected output:
2 3 5 7 11 13 17 19
# construct original array starting with k from an array of xor of all elements except elements at same index | function to construct an array with each element equal to xor of all array elements except the element at the same index ; original array ; stores bitwise xor of array ; calculate xor of all array elements ; print the original array b ; 
def constructArray(A, N, K):
    B = [0] * N
    totalXOR = A[0] ^ K
    for i in range(N):
        B[i] = totalXOR ^ A[i]
    for i in range(N):
        print(B[i], end=" ")


if __name__ == '__main__':
    A = [13, 14, 10, 6]
    K = 2
    N = len(A)
    constructArray(A, N, K)

# Expected output:
2 1 5 9
# find extra element in the second array | function to return the extra element in b [ ] ; to store the result ; find the xor of all the element of array a [ ] and array b [ ] ; 
def extraElement(A, B, n):
    ans = 0
    for i in range(n):
        ans ^= A[i]
    for i in range(n + 1):
        ans ^= B[i]
    return ans


A = [10, 15, 5]
B = [10, 100, 15, 5]
n = len(A)
print(extraElement(A, B, n))

# Expected output:
100
# hamming distance between two integers | function to calculate hamming distance ; 
def hammingDistance(n1, n2):
    x = n1 ^ n2
    setBits = 0
    while (x > 0):
        setBits += x & 1
        x >>= 1
    return setBits


if __name__ == '__main__':
    n1 = 9
    n2 = 14
    print(hammingDistance(9, 14))

# Expected output:
3
# print bitwise and set of a number n | function to find bitwise subsets naive approach ; 
def printSubsets(n):
    for i in range(n + 1):
        if ((n & i) == i):
            print(i, " ", end="")


n = 9
printSubsets(n)

# Expected output:
0  1  8  9
# find most significant set bit of a number | python program to find msb number for given n . ; to find the position of the most significant set bit ; to return the value of the number with set bit at k - th position ; 

import math


def setBitNumber(n):
    k = int(math .log(n, 2))
    return 1 << k


n = 273
print(setBitNumber(n))

# Expected output:
256
# minimum number of subsets with distinct elements | function to count subsets such that all subsets have distinct elements . ; take input and initialize res = 0 ; sort the array ; traverse the input array and find maximum frequency ; for each number find its repetition / frequency ; update res ; 
def subset(ar, n):
    res = 0
    ar .sort()
    for i in range(0, n):
        count = 1
        for i in range(n - 1):
            if ar[i] == ar[i + 1]:
                count += 1
            else:
                break
        res = max(res, count)
    return res


ar = [5, 6, 9, 3, 4, 3, 4]
n = len(ar)
print(subset(ar, n))

# Expected output:
2
# minimum number of subsets with distinct elements | function to count subsets such that all subsets have distinct elements . ; traverse the input array and store frequencies of elements ; find the maximum value in map . ; 
def subset(arr, n):
    mp = {i: 0 for i in range(10)}
    for i in range(n):
        mp[arr[i]] += 1
    res = 0
    for key, value in mp .items():
        res = max(res, value)
    return res


if __name__ == '__main__':
    arr = [5, 6, 9, 3, 4, 3, 4]
    n = len(arr)
    print(subset(arr, n))

# Expected output:
2
# rearrange array such that sum of same indexed elements is atmost k | ''function to rearrange array such that sum of similar indexed elements does not exceed k ; '' sort the array b[]  in descending order ; '' if condition fails ; '' print the array ; ''
def rearrangeArray(A, B, N, K):
    B .sort(reverse=True)
    flag = True
    for i in range(N):
        if (A[i] + B[i] > K):
            flag = False
            break
    if (flag == False):
        print("-1")
    else:
        for i in range(N):
            print(B[i], end=" ")


if __name__ == '__main__':
    A = [1, 2, 3, 4, 2]
    B = [1, 2, 3, 1, 1]
    N = len(A)
    K = 5
    rearrangeArray(A, B, N, K)

# Expected output:
3 2 1 1 1
# count rows with sum exceeding sum of the remaining matrix | ''function to count the number of rows whose sum exceeds the sum of elements of the remaining matrix ; '' stores the matrix dimensions ; '' to store the result ; '' stores the total sum of  the matrix elements ; '' calculate the total sum ; '' traverse to check for each row ; '' stores the sum of elements  of the current row ; '' calculate the sum of elements  of the current row ; '' if sum of current row exceeds  the sum of rest of the matrix ; '' increase count ; '' print the result ; ''
def countRows(mat):
    n = len(mat)
    m = len(mat[0])
    count = 0
    totalSum = 0
    for i in range(n):
        for j in range(m):
            totalSum += mat[i][j]
    for i in range(n):
        currSum = 0
        for j in range(m):
            currSum += mat[i][j]
        if (currSum > totalSum - currSum):
            count += 1
    print(count)


if __name__ == '__main__':
    mat = [[2, -1, 5], [-3, 0, -2], [5, 1, 2]]
    countRows(mat)

# Expected output:
2
# check if array contains contiguous integers with duplicates allowed | function to check whether the array contains a set of contiguous integers ; sort the array ; after sorting , check if current element is either same as previous or is one more . ; 
def areElementsContiguous(arr, n):
    arr .sort()
    for i in range(1, n):
        if (arr[i] - arr[i - 1] > 1):
            return 0
    return 1


arr = [5, 2, 3, 6, 4, 4, 6, 6]
n = len(arr)
if areElementsContiguous(arr, n):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# check if array contains contiguous integers with duplicates allowed | function to check whether the array contains a set of contiguous integers ; find maximum and minimum elements . ; there should be at least m elements in array to make them contiguous . ; create a visited array and initialize fals ; mark elements as true . ; if any element is not marked , all elements are not contiguous . ; 
def areElementsContiguous(arr, n):
    max1 = max(arr)
    min1 = min(arr)
    m = max1 - min1 + 1
    if (m > n):
        return False
    visited = [0] * m
    for i in range(0, n):
        visited[arr[i] - min1] = True
    for i in range(0, m):
        if (visited[i] == False):
            return False
    return True


arr = [5, 2, 3, 6, 4, 4, 6, 6]
n = len(arr)
if (areElementsContiguous(arr, n)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# check if array contains contiguous integers with duplicates allowed | function to check whether the array contains a set of contiguous integers ; storing elements of ' arr [ ] ' in a hash table 'us   ; as arr [ 0 ] is present in 'us   ; starting with previous smaller element of arr [ 0 ] ; if ' curr _ ele ' is present in 'us   ; increment count ; update 'curr_ele" ; starting with next greater element of arr [ 0 ] ; if ' curr _ ele ' is present in 'us   ; increment count ; update 'curr_ele" ; returns true if array contains a set of contiguous integers else returns false ; 
def areElementsContiguous(arr):
    us = set()
    for i in arr:
        us .add(i)
    count = 1
    curr_ele = arr[0] - 1
    while curr_ele in us:
        count += 1
        curr_ele -= 1
    curr_ele = arr[0] + 1
    while curr_ele in us:
        count += 1
        curr_ele += 1
    return (count == len(us))


arr = [5, 2, 3, 6, 4, 4, 6, 6]
if areElementsContiguous(arr):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# longest subarray not having more than k distinct elements | function to print the longest sub - array ; mark the element visited ; if its visited first time , then increase the counter of distinct elements by 1 ; when the counter of distinct elements increases from k , then reduce it to k ; from the left , reduce the number of time of visit ; if the reduced visited time element is not present in further segment then decrease the count of distinct elements ; increase the subsegment mark ; check length of longest sub - segment when greater then previous best then change it ; print the longest sub - segment ; 

import collections


def longest(a, n, k):
    freq = collections .defaultdict(int)
    start = 0
    end = 0
    now = 0
    l = 0
    for i in range(n):
        freq[a[i]] += 1
        if (freq[a[i]] == 1):
            now += 1
        while (now > k):
            freq[a[l]] -= 1
            if (freq[a[l]] == 0):
                now -= 1
            l += 1
        if (i - l + 1 >= end - start + 1):
            end = i
            start = l
    for i in range(start, end + 1):
        print(a[i], end=" ")


if __name__ == "__main__":
    a = [6, 5, 1, 2, 3, 2, 1, 4, 5]
    n = len(a)
    k = 3
    longest(a, n, k)

# Expected output:
1 2 3 2 1
# check if any k ranges overlap at any point | function that returns true if any k segments overlap at any point ; vector to store the starting point and the ending point ; starting points are marked by - 1 and ending points by + 1 ; sort the vector by first element ; stack to store the overlaps ; get the current element ; if it is the starting point ; push it in the stack ; it is the ending point ; pop an element from stack ; if more than k ranges overlap ; 
def kOverlap(pairs: list, k):
    vec = list()
    for i in range(len(pairs)):
        vec .append((pairs[0], -1))
        vec .append((pairs[1], 1))
    vec .sort(key=lambda a: a[0])
    st = list()
    for i in range(len(vec)):
        cur = vec[i]
        if cur[1] == -1:
            st .append(cur)
        else:
            st .pop()
        if len(st) >= k:
            return True
    return False


if __name__ == "__main__":
    pairs = list()
    pairs .append((1, 3))
    pairs .append((2, 4))
    pairs .append((3, 5))
    pairs .append((7, 10))
    n = len(pairs)
    k = 3
    if kOverlap(pairs, k):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# find smallest range containing elements from k lists | python3 program to finds out smallest range that includes elements from each of the given sorted lists . ; array for storing the current index of list i ; this function takes an k sorted lists in the form of 2d array as an argument . it finds out smallest range that includes elements from each of the k lists . ; initializing to 0 index ; for maintaining the index of list containing the minimum element ; iterating over all the list ; if every element of list [ i ] is traversed then break the loop ; find minimum value among all the list elements pointing by the ptr [ ] array ; update the index of the list ; find maximum value among all the list elements pointing by the ptr [ ] array ; if any list exhaust we will not get any better answer , so break the while loop ; updating the minrange ; 

N = 5
ptr = [0 for i in range(501)]


def findSmallestRange(arr, n, k):
    i, minval, maxval, minrange, minel, maxel, flag, minind = 0, 0, 0, 0, 0, 0, 0, 0
    for i in range(k + 1):
        ptr[i] = 0
    minrange = 10 ** 9
    while (1):
        minind = -1
        minval = 10 ** 9
        maxval = -10 ** 9
        flag = 0
        for i in range(k):
            if (ptr[i] == n):
                flag = 1
                break
            if (ptr[i] < n and arr[i][ptr[i]] < minval):
                minind = i
                minval = arr[i][ptr[i]]
            if (ptr[i] < n and arr[i][ptr[i]] > maxval):
                maxval = arr[i][ptr[i]]
        if (flag):
            break
        ptr[minind] += 1
        if ((maxval - minval) < minrange):
            minel = minval
            maxel = maxval
            minrange = maxel - minel
    print("The smallest range is [", minel, maxel, "]")


arr = [[4, 7, 9, 12, 15], [0, 8, 10, 14, 20], [6, 12, 16, 30, 50]]
k = len(arr)
findSmallestRange(arr, N, k)

# Expected output:
The smallest range is [ 6 8 ]
# find largest d in array such that a + b + c = d | function to find largest d ; sort the array in ascending order ; iterating from backwards to find the required largest d ; since all four a , b , c , d should be distinct ; if the current combination of j , k , l in the set is equal to s [ i ] return this value as this would be the largest d since we are iterating in descending order ; 
def findLargestd(S, n):
    found = False
    S .sort()
    for i in range(n - 1, -1, -1):
        for j in range(0, n):
            if (i == j):
                continue
            for k in range(j + 1, n):
                if (i == k):
                    continue
                for l in range(k + 1, n):
                    if (i == l):
                        continue
                    if (S[i] == S[j] + S[k] + S[l]):
                        found = True
                        return S[i]
    if (found == False):
        return -1


S = [2, 3, 5, 7, 12]
n = len(S)
ans = findLargestd(S, n)
if (ans == -1):
    print("No Solution")
else:
    print("Largest d such that a + b +", "c = d is", ans)

# Expected output:
Largest d such that a + b + c = d is 12
# find largest d in array such that a + b + c = d | the function finds four elements with given sum x ; store sums ( a + b ) of all pairs ( a , b ) in a hash table ; traverse through all pairs and find ( d - c ) is present in hash table ; if d - c is present in hash table , ; making sure that all elements are distinct array elements and an element is not considered more than once . ; 
def findFourElements(arr, n):
    mp = dict()
    for i in range(n - 1):
        for j in range(i + 1, n):
            mp[arr[i] + arr[j]] = (i, j)
    d = -10 ** 9
    for i in range(n - 1):
        for j in range(i + 1, n):
            abs_diff = abs(arr[i] - arr[j])
            if abs_diff in mp .keys():
                p = mp[abs_diff]
                if (p[0] != i and p[0] != j and p[1] != i and p[1] != j):
                    d = max(d, max(arr[i], arr[j]))
    return d


arr = [2, 3, 5, 7, 12]
n = len(arr)
res = findFourElements(arr, n)
if (res == -10 ** 9):
    print("No Solution.")
else:
    print(res)

# Expected output:
12
# maximize count of elements that can be selected having minimum difference between their sum and k | function to count maximum number of elements that can be selected ; sort he array ; traverse the array ; add current element to the sum ; if sum exceeds k ; increment count ; return the count ; 
def CountMaximum(arr, n, k):
    arr .sort()
    Sum, count = 0, 0
    for i in range(0, n):
        Sum += arr[i]
        if (Sum > k):
            break
        count += 1
    return count


arr = [30, 30, 10, 10]
n = len(arr)
k = 50
print(CountMaximum(arr, n, k))

# Expected output:
3
# sort the array in a given index range | function to sort the elements of the array from index a to index b ; variables to store start and end of the index range ; temporary array ; sort the temporary array ; modifying original array with temporary array elements ; print the modified array ; 
def partSort(arr, N, a, b):
    l = min(a, b)
    r = max(a, b)
    temp = [0 for i in range(r - l + 1)]
    j = 0
    for i in range(l, r + 1, 1):
        temp[j] = arr[i]
        j += 1
    temp .sort(reverse=False)
    j = 0
    for i in range(l, r + 1, 1):
        arr[i] = temp[j]
        j += 1
    for i in range(0, N, 1):
        print(arr[i], end=" ")


if __name__ == '__main__':
    arr = [7, 8, 4, 5, 2]
    a = 1
    b = 4
    N = len(arr)
    partSort(arr, N, a, b)

# Expected output:
7 2 4 5 8
# move all zeroes to end of array | function which pushes all zeros to end of an array . ; count of non - zero elements ; traverse the array . if element encountered is non - zero , then replace the element at index ' count ' with this element ; here count is incremented ; now all non - zero elements have been shifted to front and ' count ' is set as index of first 0. make all elements 0 from count to end . ; 
def pushZerosToEnd(arr, n):
    count = 0
    for i in range(n):
        if arr[i] != 0:
            arr[count] = arr[i]
            count += 1
    while count < n:
        arr[count] = 0
        count += 1


arr = [1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9]
n = len(arr)
pushZerosToEnd(arr, n)
print("Array after pushing all zeros to end of array:")
print(arr)

# Expected output:
Array after pushing all zeros to end of array:
[1, 9, 8, 4, 2, 7, 6, 9, 0, 0, 0, 0]
# rearrange positive and negative numbers with constant extra space | python implementation of the above approach ; loop until arr [ i ] < 0 and still inside the array ; loop until arr [ j ] > 0 and still inside the array ; if i is less than j ; 
def RearrangePosNeg(arr, n):
    i = 0
    j = n - 1
    while (True):
        while (arr[i] < 0 and i < n):
            i += 1
        while (arr[j] > 0 and j >= 0):
            j -= 1
        if (i < j):
            arr[i], arr[j] = arr[j], arr[i]
        else:
            break


arr = [-12, 11, -13, -5, 6, -7, 5, -3, -6]
n = len(arr)
RearrangePosNeg(arr, n)
print(*arr)

# Expected output:
-12 -6 -13 -5 -3 -7 5 6 11
# find the player to be able to replace the last element that can be replaced by its divisors | function to find the winner of the game played based on given conditions ; a wins if size of array is odd ; otherwise , b wins ; 
def winner(arr, N):
    if (N % 2 == 1):
        print("A")
    else:
        print("B")


if __name__ == '__main__':
    arr = [24, 45, 45, 24]
    N = len(arr)
    winner(arr, N)

# Expected output:
B
# queries to calculate sum of array elements present at every yth index starting from the index x | python program for the above approach ; function to sum of arr [ x ] + arr [ x + y ] + arr [ x + 2 * y ] + ... for all possible values of x and y , where y is less than or equal to sqrt ( n ) . ; iterate over all possible values of x ; precompute for all possible values of an expression such that y <= sqrt ( n ) ; if i + j less than n ; update dp [ i ] [ j ] ; update dp [ i ] [ j ] ; function to find the sum of arr [ x ] + arr [ x + y ] + arr [ x + 2 * y ] + ... for all queries ; dp [ x ] [ y ] : stores sum of arr [ x ] + arr [ x + y ] + arr [ x + 2 * y ] + ... ; traverse the query array , q [ ] [ ] ; if y is less than or equal to sqrt ( n ) ; stores the sum of arr [ x ] + arr [ x + y ] + arr [ x + 2 * y ] + ... ; traverse the array , arr [ ] ; update sum ; update x ; 

import math
sz = 20
sqr = int(math .sqrt(sz)) + 1


def precomputeExpressionForAllVal(arr, N, dp):
    for i in range(N - 1, -1, -1):
        for j in range(1, int(math .sqrt(N)) + 1):
            if (i + j < N):
                dp[i][j] = arr[i] + dp[i + j][j]
            else:
                dp[i][j] = arr[i]


def querySum(arr, N, Q, M):
    dp = [[0 for x in range(sz)]for x in range(sqr)]
    precomputeExpressionForAllVal(arr, N, dp)
    for i in range(0, M):
        x = Q[i][0]
        y = Q[i][1]
        if (y <= math .sqrt(N)):
            print(dp[x][y])
            continue
        sum = 0
        while (x < N):
            sum += arr[x]
            x += y
        print(sum)


arr = [1, 2, 7, 5, 4]
Q = [[2, 1], [3, 2]]
N = len(arr)
M = len(Q[0])
querySum(arr, N, Q, M)

# Expected output:
16
5