giulio98/xlcost-single-prompt huggingface dataset:
# find prime number k in an array such that ( a [ i ] % k ) is maximum | python 3 implementation of the approach ; function to return the required prime number from the array ; find maximum value in the array ; use sieve to find all prime numbers less than or equal to max_val create a boolean array " prime [ 0 . . n ] " . a value in prime [ i ] will finally be false if i is not a prime , else true . ; remaining part of sieve ; if prime [ p ] is not changed , then it is a prime ; update all multiples of p ; to store the maximum prime number ; if current element is prime then update the maximum prime ; return the maximum prime number from the array ; 

from math import sqrt


def getPrime(arr, n):
    max_val = arr[0]
    for i in range(len(arr)):
        if (arr[i] > max_val):
            max_val = arr[i]
    prime = [True for i in range(max_val + 1)]
    prime[0] = False
    prime[1] = False
    for p in range(2, int(sqrt(max_val)) + 1, 1):
        if (prime[p]):
            for i in range(p * 2, max_val + 1, p):
                prime[i] = False
    maximum = -1
    for i in range(n):
        if (prime[arr[i]]):
            maximum = max(maximum, arr[i])
    return maximum


if __name__ == '__main__':
    arr = [2, 10, 15, 7, 6, 8, 13]
    n = len(arr)
    print(getPrime(arr, n))

# Expected output:
13
# minimum integer such that it leaves a remainder 1 on dividing with any element from the range [ 2 , n ] | python3 implementation of the approach ; function to return the smallest number which on dividing with any element from the range [ 2 , n ] leaves a remainder of 1 ; find the lcm of the elements from the range [ 2 , n ] ; return the required number ; 

from math import gcd


def getMinNum(N):
    lcm = 1
    for i in range(2, N + 1):
        lcm = ((i * lcm) // (gcd(i, lcm)))
    return (lcm + 1)


if __name__ == "__main__":
    N = 5
    print(getMinNum(N))

# Expected output:
61
# maximum number of edges in bipartite graph | function to return the maximum number of edges possible in a bipartite graph with n vertices ; 
def maxEdges(N):
    edges = 0
    edges = (N * N) // 4
    return edges


if __name__ == "__main__":
    N = 5
    print(maxEdges(N))

# Expected output:
6
# check if the robot is within the bounds of the grid after given moves | function that returns true if the robot is safe ; if current move is " l " then increase the counter of coll ; if value of coll is equal to column then break ; if current move is " r " then increase the counter of colr ; if value of colr is equal to column then break ; if current move is " u " then increase the counter of rowu ; if value of rowu is equal to row then break ; if current move is " d " then increase the counter of rowd ; if value of rowd is equal to row then break ; if robot is within the bounds of the grid ; unsafe ; 
def isSafe(N, M, str):
    coll = 0
    colr = 0
    rowu = 0
    rowd = 0
    for i in range(len(str)):
        if (str[i] == 'L'):
            coll += 1
            if (colr > 0):
                colr -= 1
            if (coll == M):
                break
        elif (str[i] == 'R'):
            colr += 1
            if (coll > 0):
                coll -= 1
            if (colr == M):
                break
        elif (str[i] == 'U'):
            rowu += 1
            if (rowd > 0):
                rowd -= 1
            if (rowu == N):
                break
        elif (str[i] == 'D'):
            rowd += 1
            if (rowu > 0):
                rowu -= 1
            if (rowd == N):
                break
    if (abs(rowd) < N and abs(rowu) < N and abs(coll) < M and abs(colr) < M):
        return True
    return False


if __name__ == '__main__':
    N = 1
    M = 1
    str = "R"
    if (isSafe(N, M, str)):
        print("Yes")
    else:
        print("No")

# Expected output:
No
# find permutation of first n natural numbers that satisfies the given condition | function to find permutation ( p ) of first n natural numbers such that there are exactly k elements of permutation such that gcd ( p [ i ] , i ) > 1 ; first place all the numbers in their respective places ; modify for first n - k integers ; in first index place n - k ; print the permutation ; 
def Permutation(n, k):
    p = [0 for i in range(n + 1)]
    for i in range(1, n + 1):
        p[i] = i
    for i in range(1, n - k):
        p[i + 1] = i
    p[1] = n - k
    for i in range(1, n + 1):
        print(p[i], end=" ")


if __name__ == '__main__':
    n = 5
    k = 2
    Permutation(n, k)

# Expected output:
3 1 2 4 5
# count number of 1 s in the array after n moves | function to count number of 1 's in the array after performing n moves ; if index is multiple of move number ; arr [ j - 1 ] = 1 convert 0 to 1 ; arr [ j - 1 ] = 0 convert 1 to 0 ; count number of 1 's ; count += 1 count number of 1 's ; 
def countOnes(arr, N):
    for i in range(1, N + 1, 1):
        for j in range(i, N + 1, 1):
            if (j % i == 0):
                if (arr[j - 1] == 0):
                    arr[j - 1] = 1
                else:
                    arr[j - 1] = 0
    count = 0
    for i in range(N):
        if (arr[i] == 1):
            count += 1

    return count


if __name__ == '__main__':
    N = 10
    arr = [0 for i in range(10)]
    ans = countOnes(arr, N)
    print(ans)

# Expected output:
3
# number of positions such that adding k to the element is greater than sum of all other elements | function that will find out the valid position ; find sum of all the elements ; adding k to the element and check whether it is greater than sum of all other elements ; 
def validPosition(arr, N, K):
    count = 0
    sum = 0
    for i in range(N):
        sum += arr[i]
    for i in range(N):
        if ((arr[i] + K) > (sum - arr[i])):
            count += 1
    return count


arr = [2, 1, 6, 7]
K = 4
N = len(arr)
print(validPosition(arr, N, K))

# Expected output:
1
# count unique numbers that can be generated from n by adding one and removing trailing zeros | function to count the unique numbers ; if the number has already been visited ; insert the number to the set ; first step ; second step remove trailing zeros ; recur again for the new number ; 
def count_unique(s, n):
    if (s .count(n)):
        return
    s .append(n)
    n += 1
    while (n % 10 == 0):
        n = n // 10
    count_unique(s, n)


if __name__ == "__main__":
    n = 10
    s = []
    count_unique(s, n)
    print(len(s))

# Expected output:
19
# find element with the maximum set bits in an array | function to return the element from the array which has the maximum set bits ; to store the required element and the maximum set bits so far ; count of set bits in the current element ; update the max ; 
def maxBitElement(arr, n):
    num = 0
    max = -1
    for i in range(n):
        cnt = bin(arr[i]).count('1')
        if (cnt > max):
            max = cnt
            num = arr[i]
    return num


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

# Expected output:
7
# count pairs with average present in the same array | python 3 implementation of the approach ; function to return the count of valid pairs ; frequency array twice the original size to hold negative elements as well ; update the frequency of each of the array element ; if say x = - 1000 then we will place the frequency of - 1000 at ( - 1000 + 1000 = 0 ) a [ 0 ] index ; to store the count of valid pairs ; remember we will check only for ( even , even ) or ( odd , odd ) pairs of indexes as the average of two consecutive elements is a floating point number ; 

N = 1000


def countPairs(arr, n):
    size = (2 * N) + 1
    freq = [0 for i in range(size)]
    for i in range(n):
        x = arr[i]
        freq[x + N] += 1
    ans = 0
    for i in range(size):
        if (freq[i] > 0):
            ans += int(((freq[i]) * (freq[i] - 1)) / 2)
            for j in range(i + 2, 2001, 2):
                if (freq[j] > 0 and (freq[int((i + j) / 2)] > 0)):
                    ans += (freq[i] * freq[j])
    return ans


if __name__ == '__main__':
    arr = [4, 2, 5, 1, 3, 5]
    n = len(arr)
    print(countPairs(arr, n))

# Expected output:
7
# given two arrays count all pairs whose sum is an odd number | function that returns the number of pairs ; count of odd and even numbers ; traverse in the first array and count the number of odd and evene numbers in them ; traverse in the second array and count the number of odd and evene numbers in them ; count the number of pairs ; return the number of pairs ; 
def count_pairs(a, b, n, m):
    odd1 = 0
    even1 = 0
    odd2 = 0
    even2 = 0
    for i in range(n):
        if (a[i] % 2):
            odd1 += 1
        else:
            even1 += 1
    for i in range(m):
        if (b[i] % 2):
            odd2 += 1
        else:
            even2 += 1
    pairs = (min(odd1, even2) + min(odd2, even1))
    return pairs


if __name__ == '__main__':
    a = [9, 14, 6, 2, 11]
    b = [8, 4, 7, 20]
    n = len(a)
    m = len(b)
    print(count_pairs(a, b, n, m))

# Expected output:
3
# print steps to make a number in form of 2 ^ x | function to find the leftmost unset bit in a number . ; function that perform the step ; find the leftmost unset bit ; if the number has no bit unset , it means it is in form 2 ^ x - 1 ; count the steps ; iterate till number is of form 2 ^ x - 1 ; at even step increase by 1 ; odd step xor with any 2 ^ m - 1 ; find the leftmost unset bit ; 2 ^ m - 1 ; perform the step ; increase the steps ; 
def find_leftmost_unsetbit(n):
    ind = -1
    i = 1
    while (n):
        if ((n % 2) != 1):
            ind = i
        i += 1
        n >>= 1
    return ind


def perform_steps(n):
    left = find_leftmost_unsetbit(n)
    if (left == -1):
        print("No steps required")
        return
    step = 1
    while (find_leftmost_unsetbit(n) != -1):
        if (step % 2 == 0):
            n += 1
            print("Step", step, ":Increaseby1")
        else:
            m = find_leftmost_unsetbit(n)
            num = (2 ** m) - 1
            n = n ^ num
            print("Step", step, ": Xor with", num)
        step += 1


n = 39
perform_steps(n)

# Expected output:
Step 1 : Xor with 31
Step 2 :Increaseby1
Step 3 : Xor with 7
Step 4 :Increaseby1
# determine the position of the third person on regular n sided polygon | function to find out the number of that vertices ; another person can 't stand on  vertex on which 2 children stand. ; calculating minimum jumps from each vertex . ; calculate sum of jumps . ; 
def vertices(N, A, B):
    position = 0
    miniSum = 10 ** 9
    Sum = 0
    for i in range(1, N + 1):
        if (i == A or i == B):
            continue
        else:
            x = abs(i - A)
            y = abs(i - B)
            Sum = x + y
            if (Sum < miniSum):
                miniSum = Sum
                position = i
    return position


N = 3
A = 1
B = 2
print("Vertex = ", vertices(N, A, B))

# Expected output:
Vertex =  3
# find sum of factorials in an array | function to return the factorial of n ; function to return the sum of factorials of the array elements ; to store the required sum ; add factorial of all the elements ; 
def factorial(n):
    f = 1
    for i in range(1, n + 1):
        f *= i
    return f


def sumFactorial(arr, n):
    s = 0
    for i in range(0, n):
        s += factorial(arr[i])
    return s


arr = [7, 3, 5, 4, 8]
n = len(arr)
print(sumFactorial(arr, n))

# Expected output:
45510
# highest power of 2 that divides a number represented in binary | function to return the highest power of 2 which divides the given binary number ; to store the highest required power of 2 ; counting number of consecutive zeros from the end in the given binary string ; 
def highestPower(str, length):
    ans = 0
    for i in range(length - 1, -1, -1):
        if (str[i] == '0'):
            ans += 1
        else:
            break
    return ans


def main():
    str = "100100"
    length = len(str)
    print(highestPower(str, length))


if __name__ == '__main__':
    main()

# Expected output:
2
# number of ways to arrange k different objects taking n objects at a time | python3 implementation of the approach ; function to return n ! % p ; res = 1 initialize result ; iterative function to calculate ( x ^ y ) % p in o ( log y ) ; x = x % p update x if it is more than or equal to p ; if y is odd , multiply x with result ; y must be even now y = y >> 1 y = y / 2 ; returns n ^ ( - 1 ) mod p ; returns ncr % p using fermat 's little theorem. ; base case ; fifactorial array so that we can find afactorial of r , n and n - r ; function to return the number of ways to arrange k different objects taking n objects at a time ; 

mod = 10 ** 9 + 7


def factorial(n, p):
    res = 1
    for i in range(2, n + 1):
        res = (res * i) % p
    return res


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


def modInverse(n, p):
    return power(n, p - 2, p)


def nCrModP(n, r, p):
    if (r == 0):
        return 1
    fac = [0 for i in range(n + 1)]
    fac[0] = 1
    for i in range(1, n + 1):
        fac[i] = fac[i - 1] * i % p
    return (fac[n] * modInverse(fac[r], p) %
            p * modInverse(fac[n - r], p) % p) % p


def countArrangements(n, k, p):
    return (factorial(n, p) * nCrModP(k, n, p)) % p


N = 5
K = 8
print(countArrangements(N, K, mod))

# Expected output:
6720
# find maximum product of digits among numbers less than or equal to n | function that returns the maximum product of digits among numbers less than or equal to n ; 
def maxProd(N):
    if (N == 0):
        return 1
    if (N < 10):
        return N
    return max(maxProd(N // 10) * (N % 10), maxProd(N // 10 - 1) * 9)


N = 390
print(maxProd(N))

# Expected output:
216
# check if a number from every row can be selected such that xor of the numbers is greater than zero | python3 program to implement the above approach ; function to check if a number from every row can be selected such that xor of the numbers is greater than zero ; find the xor of first column for every row ; if xorr is 0 ; traverse in the matrix ; check is atleast 2 distinct elements ; 

N = 2
M = 3


def check(mat):
    xorr = 0
    for i in range(N):
        xorr ^= mat[i][0]
    if (xorr != 0):
        return True
    for i in range(N):
        for j in range(1, M):
            if (mat[i][j] != mat[i][0]):
                return True
    return False


mat = [[7, 7, 7], [10, 10, 7]]
if (check(mat)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# sum of the series 1 , 2 , 4 , 3 , 5 , 7 , 9 , 6 , 8 , 10 , 11 , 13. . till n | function to find the sum of first n odd numbers ; function to find the sum of first n even numbers ; function to overall find the sum of series ; initial odd numbers ; initial even numbers ; first power of 2 ; check for parity for odd / even ; counts the sum ; get the minimum out of remaining num or power of 2 ; decrease that much numbers from num ; if the segment has odd numbers ; summate the odd numbers by exclusion ; increase number of odd numbers ; if the segment has even numbers ; summate the even numbers by exclusion ; increase number of even numbers ; next set of numbers ; change parity for odd / even ; 
def sumodd(n):
    return (n * n)


def sumeven(n):
    return (n * (n + 1))


def findSum(num):
    sumo = 0
    sume = 0
    x = 1
    cur = 0
    ans = 0
    while (num > 0):
        inc = min(x, num)
        num -= inc
        if (cur == 0):
            ans = ans + sumodd(sumo + inc) - sumodd(sumo)
            sumo += inc
        else:
            ans = ans + sumeven(sume + inc) - sumeven(sume)
            sume += inc
        x *= 2
        cur ^= 1
    return ans


n = 4
print(findSum(n))

# Expected output:
10
# find the nth term of the given series | function to return the nth term of the given series ; 
def oddTriangularNumber(N):
    return (N * ((2 * N) - 1))


if __name__ == '__main__':
    N = 3
    print(oddTriangularNumber(N))

# Expected output:
15
# check if given two straight lines are identical or not | function to check if they are identical ; 
def idstrt(a1, b1, c1, a2, b2, c2):
    if ((a1 // a2 == b1 // b2) and (a1 // a2 ==
                                    c1 // c2) and (b1 // b2 == c1 // c2)):
        print("The given straight lines", "are identical")
    else:
        print("The given straight lines", "are not identical")


a1, b1 = -2, 4
c1, a2 = 3, -6
b2, c2 = 12, 9
idstrt(a1, b1, c1, a2, b2, c2)

# Expected output:
The given straight lines are identical
# count arrays of length k whose product of elements is same as that of given array | python 3 implementation of the approach ; to store the smallest prime factor for every number ; initialize map to store count of prime factors ; function to calculate spf ( smallest prime factor ) for every number till maxn ; marking smallest prime factor for every number to be itself ; separately marking spf for every even number as 2 ; checking if i is prime ; marking spf for all numbers divisible by i ; marking spf [ j ] if it is not previously marked ; function to factorize using spf and store in cnt ; function to return n ! % p ; initialize result ; iterative function to calculate ( x ^ y ) % p in o ( log y ) ; initialize result ; update x if it is >= p ; if y is odd , multiply x with result ; y must be even now y = y / 2 ; function that returns n ^ ( - 1 ) mod p ; function that returns ncr % p using fermat 's little theorem ; base case ; fill factorial array so that we can find all factorial of r , n and n - r ; function to return the count the number of possible arrays mod p of length k such that the product of all elements of that array is equal to the product of all elements of the given array of length n ; initialize result ; call sieve to get spf ; factorize arr [ i ] , count and store its factors in cnt ; 

from math import sqrt
MAXN = 100001
mod = 1000000007
spf = [0 for i in range(MAXN)]
cnt = {i: 0 for i in range(10)}


def sieve():
    spf[1] = 1
    for i in range(2, MAXN):
        spf[i] = i
    for i in range(4, MAXN, 2):
        spf[i] = 2
    for i in range(3, int(sqrt(MAXN)) + 1, 1):
        if (spf[i] == i):
            for j in range(i * i, MAXN, i):
                if (spf[j] == j):
                    spf[j] = i


def factorize(f):
    while (f > 1):
        x = spf[f]
        while (f % x == 0):
            cnt[x] += 1
            f = int(f / x)


def factorial(n, p):
    res = 1
    for i in range(2, n + 1, 1):
        res = (res * i) % p
    return res


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


def modInverse(n, p):
    return power(n, p - 2, p)


def nCrModP(n, r, p):
    if (r == 0):
        return 1
    fac = [0 for i in range(n + 1)]
    fac[0] = 1
    for i in range(1, n + 1, 1):
        fac[i] = fac[i - 1] * i % p
    return (fac[n] * modInverse(fac[r], p) %
            p * modInverse(fac[n - r], p) % p) % p


def countArrays(arr, N, K, P):
    res = 1
    sieve()
    for i in range(N):
        factorize(arr[i])
    for key, value in cnt .items():
        ci = value
        res = (res * nCrModP(ci + K - 1, K - 1, P)) % P
    return res


if __name__ == '__main__':
    arr = [1, 3, 5, 2]
    K = 3
    N = len(arr)
    print(countArrays(arr, N, K, mod))

# Expected output:
27
# count different numbers possible using all the digits their frequency times | python3 implementation of the above approach ; initialize an array to store factorial values ; function to calculate and store x ! values ; iterative function to calculate ( x ^ y ) % p in o ( log y ) ; x = x % p update x if it is more than or equal to p ; if y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; function that return modular inverse of x under modulo p ; function that returns the count of different number possible by using all the digits its frequency times ; preprocess factorial values ; initialize the result and sum of aint the frequencies ; calculate the sum of frequencies ; putting res equal to x ! ; multiplying res with modular inverse of x0 ! , x1 ! , . . , x9 ! ; 

MAXN = 100000
MOD = 1000000007
fact = [0] * MAXN


def factorial():
    fact[0] = 1
    for i in range(1, MAXN):
        fact[i] = (fact[i - 1] * i) % MOD


def power(x, y, p):

    res = 1

    x = x % p

    while (y > 0):
        if (y & 1):
            res = (res * x) % p
        y = y >> 1
        x = (x * x) % p

    return res


def modInverse(x, p):
    return power(x, p - 2, p)


def countDifferentNumbers(arr, P):
    factorial()
    res = 0
    X = 0
    for i in range(10):
        X += arr[i]
    res = fact[X]
    for i in range(10):
        if (arr[i] > 1):
            res = (res * modInverse(fact[arr[i]], P)) % P

    return res


if __name__ == "__main__":
    arr = [1, 0, 2, 0, 0, 7, 4, 0, 0, 3]
    print(countDifferentNumbers(arr, MOD))

# Expected output:
245044800
# equation of straight line passing through a given point which bisects it into two equal line segments | function to print the equation of the required line ; 
def line(x0, y0):
    c = 2 * y0 * x0
    print(y0, "x", "+", x0, "y=", c)


if __name__ == '__main__':
    x0 = 4
    y0 = 3
    line(x0, y0)

# Expected output:
3 x + 4 y= 24
# find the original matrix when largest element in a row and a column are given | python3 implementation of the approach ; function that prints the original matrix ; iterate in the row ; iterate in the column ; if previously existed an element ; 

N = 3
M = 7


def printOriginalMatrix(a, b, mat):
    for i in range(N):
        for j in range(M):
            if (mat[i][j] == 1):
                print(min(a[i], b[j]), end=" ")
            else:
                print(0, end=" ")
        print()


if __name__ == "__main__":
    a = [2, 1, 3]
    b = [2, 3, 0, 0, 2, 0, 1]
    mat = [[1, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1], [1, 1, 0, 0, 0, 0, 0]]
    printOriginalMatrix(a, b, mat)

# Expected output:
2 0 0 0 2 0 0 
0 0 0 0 0 0 1 
2 3 0 0 0 0 0
# calculate the loss incurred in selling the given items at discounted price | function to return the x % of n ; function to return the total loss ; to store the total loss ; original price of the item ; the price at which the item will be sold ; the discounted price of the item ; loss incurred ; 
def percent(n, x):
    p = (int)(n) * x
    p /= 100
    return p


def getLoss(price, quantity, X, n):
    loss = 0
    for i in range(n):
        originalPrice = price[i]
        sellingPrice = originalPrice + percent(originalPrice, X[i])
        afterDiscount = sellingPrice - percent(sellingPrice, X[i])
        loss += ((originalPrice - afterDiscount) * quantity[i])
    return round(loss, 2)


price = [20, 48, 200, 100]
quantity = [20, 48, 1, 1]
X = [0, 48, 200, 5]
n = len(X)
print(getLoss(price, quantity, X, n))

# Expected output:
1330.17
# maximum difference between two elements in an array | function to return the maximum absolute difference between any two elements of the array ; to store the minimum and the maximum elements from the array ; 
def maxAbsDiff(arr, n):
    minEle = arr[0]
    maxEle = arr[0]
    for i in range(1, n):
        minEle = min(minEle, arr[i])
        maxEle = max(maxEle, arr[i])
    return (maxEle - minEle)


arr = [2, 1, 5, 3]
n = len(arr)
print(maxAbsDiff(arr, n))

# Expected output:
4