giulio98/xlcost-single-prompt huggingface dataset:
# sum of elements of a geometric progression ( gp ) in a 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 + 1
    d = arr[1] // arr[0]
    ans = arr[left - 1]
    if d == 1:
        ans = ans * d * k
    else:
        ans = ans * (d ** k - 1) // (d - 1)
    return ans


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

# Expected output:
28
124
480
# find the first and last m digits from k | python3 program to implement the above approach ; function to find a ^ b modulo m ; function to find the first and last m digits from n ^ k ; calculate last m digits ; calculate first m digits ; extract the number after decimal ; find 10 ^ y ; move the decimal point m - 1 digits forward ; print the result ; 

from math import *


def modPower(a, b, M):
    res = 1
    while (b):
        if (b & 1):
            res = res * a % M
        a = a * a % M
        b >>= 1
    return res


def findFirstAndLastM(N, K, M):
    lastM = modPower(N, K, int(pow(10, M)))
    firstM = 0
    y = K * log10(N * 1.0)
    y = y - int(y)
    temp = pow(10.0, y)
    firstM = int(temp * pow(10, M - 1))
    print(firstM, lastM)


N = 12
K = 12
M = 4
findFirstAndLastM(N, K, M)

# Expected output:
8916 8256
# minimize increment / decrement of array elements to make each modulo k equal | python3 program for the above approach ; function to find the minimum operations required to make the modulo of each element of the array equal to each other ; variable to store minimum operation required ; to store operation required to make all modulo equal ; iterating through all possible modulo value ; iterating through all different modulo obtained so far ; calculating oprn required to make all modulos equal to x ; checking the operations that will cost less ; check operation that will cost less ; update the minimum number of operations ; returning the answer ; function to store different modulos ; set to store all different modulo ; map to store count of all different modulo obtained ; storing all different modulo count ; insert into the set ; increment count ; function call to return value of min oprn required ; 

import sys
from collections import defaultdict


def Find_min(diff_mod, count_mod, k):
    min_oprn = sys .maxsize
    oprn = 0
    for x in range(k):
        oprn = 0
        for w in diff_mod:
            if (w != x):
                if (w == 0):
                    oprn += (min(x, k - x) * count_mod[w])
                else:
                    oprn += (min(abs(x - w), k + x - w) * count_mod[w])
        if (oprn < min_oprn):
            min_oprn = oprn
    return min_oprn


def Cal_min(arr, n, k):
    diff_mod = set([])
    count_mod = defaultdict(int)
    for i in range(n):
        diff_mod .add(arr[i] % k)
        count_mod[arr[i] % k] += 1
    return Find_min(diff_mod, count_mod, k)


if __name__ == "__main__":
    arr = [2, 35, 48, 23, 52]
    n = len(arr)
    k = 3
    print(Cal_min(arr, n, k))

# Expected output:
2
# minimize steps required to obtain sorted order of an array | function to find gcd of two numbers ; function to calculate the lcm of array elements ; initialize result ; function to find minimum steps required to obtain sorted sequence ; inititalize dat [ ] array for direct address table . ; calculating steps required for each element to reach its sorted position ; calculate lcm of the array ; 
def gcd(a, b):
    if (b == 0):
        return a
    return gcd(b, a % b)


def findlcm(arr, n):
    ans = 1
    for i in range(1, n + 1):
        ans = ((arr[i] * ans) // (gcd(arr[i], ans)))
    return ans


def minimumSteps(arr, n):
    dat = [0] * (n + 1)
    for i in range(1, n + 1):
        dat[arr[i - 1]] = i
    b = [0] * (n + 1)
    j = 0
    for i in range(1, n + 1):
        c = 1
        j = dat[i]
        while (j != i):
            c += 1
            j = dat[j]
        b[i] = c
    print(findlcm(b, n))


arr = [5, 1, 4, 3, 2, 7, 6]
N = len(arr)
minimumSteps(arr, N)

# Expected output:
6
# largest ratio contiguous subarray | python3 program for the above approach ; function to return maximum of two double values ; check if a is greater than b then return a ; function that returns the ratio of max ratio subarray ; variable to store the maximum ratio ; compute the product while traversing for subarrays ; calculate the ratio ; update max ratio ; print the answer ; 

import sys


def maximum(a, b):
    if (a > b):
        return a
    return b


def maxSubarrayRatio(arr, n):
    maxRatio = -sys .maxsize - 1
    for i in range(n):
        for j in range(i, n):
            ratio = arr[i]
            for k in range(i + 1, j + 1):
                ratio = ratio // arr[k]
            maxRatio = maximum(maxRatio, ratio)
    return int(maxRatio)


if __name__ == "__main__":
    arr = [2, 2, 4, -0.2, -1]
    n = len(arr)
    print(maxSubarrayRatio(arr, n))

# Expected output:
20
# even perfect number | python3 program for the above approach ; function to check for perfect number ; find a number close to 2 ^ q - 1 ; calculate q - 1 ; condition of perfect number ; check whether q is prime or not ; check whether 2 ^ q - 1 is a prime number or not ; function to check for prime number ; check whether it is equal to 2 or 3 ; check if it can be divided by 2 and 3 then it is not prime number ; check whether the given number be divide by other prime numbers ; 

import math


def isPrime(n):
    if (n <= 1):
        return bool(False)
    elif (n == 2 or n == 3):
        return bool(True)
    else:
        if (n % 2 == 0 or n % 3 == 0):
            return bool(False)
        for i in range(5, sqrt(n + 1) + 1, 6):
            if (n % i == 0 or n % (i + 2) == 0):
                return bool(False)
        return bool(True)


def check(num):
    root = (int)(math .sqrt(num))
    poww = (int)(math .log(root) / math .log(2))
    if (num == (int)(pow(2, poww) * (pow(2, poww + 1) - 1))):
        if (isPrime(poww + 1)):
            if (isPrime((int)(pow(2, poww + 1)) - 1)):
                print("Yes")
            else:
                print("No")
        else:
            print("No")
    else:
        print("No")


num = 6
check(num)

# Expected output:
Yes
# twin pythagorean triplets in an array | function to check if there exist a twin pythagorean triplet in the given array ; loop to check if there is a pythagorean triplet in the array ; check if there is consecutive triple ; calculate square of array elements ; 
def isTriplet(ar, n):
    for i in range(n):
        for j in range(i + 1, n):
            for k in range(j + 1, n):
                if (abs(ar[i] - ar[j]) == 1 or abs(ar[j] - ar[k])
                        == 1 or abs(ar[i] - ar[k]) == 1):
                    x = ar[i] * ar[i]
                    y = ar[j] * ar[j]
                    z = ar[k] * ar[k]
                    if (x == y + z or y == x + z or z == x + y):
                        return True
    return False


if __name__ == '__main__':
    arr = [3, 1, 4, 6, 5]
    ar_size = len(arr)
    if isTriplet(arr, ar_size):
        print('Yes')
    else:
        print('No')

# Expected output:
Yes
# pair with min absolute difference and whose product is n + 1 or n + 2 | python3 program for the above approach ; function to prpair ( a , b ) such that a * b = n + 1 or n + 2 ; loop to iterate over the desired possible values ; check for condition 1 ; check for condition 2 ; 

from math import sqrt, ceil, floor


def closestDivisors(n):
    for i in range(ceil(sqrt(n + 2)), -1, -1):
        if ((n + 1) % i == 0):
            print(i, ",", (n + 1) // i)
            break
        if ((n + 2) % i == 0):
            print(i, ",", (n + 2) // i)
            break


if __name__ == '__main__':
    N = 123
    closestDivisors(N)

# Expected output:
5 , 25
# is it possible to reach n and m from 1 and 0 respectively as per given condition | function that find given x and y is possible or not ; check if x is less than 2 and y is not equal to 0 ; perform subtraction ; check if y is divisible by 2 and greater than equal to 0 ; 
def is_possible(x, y):
    if (x < 2 and y != 0):
        return false
    y = y - x + 1
    if (y % 2 == 0 and y >= 0):
        return True
    else:
        return False


if __name__ == '__main__':
    x = 5
    y = 2
    if (is_possible(x, y)):
        print("Yes")
    else:
        print("No")

# Expected output:
No
# count of integers up to n which are non divisors and non coprime with n | function to return the count of integers less than n satisfying given conditions ; stores euler counts ; store divisor counts ; based on sieve of eratosthenes ; update phi values of all multiples of i ; update count of divisors ; return the final count ; 
def count(n):
    phi = [0] * (n + 1)
    divs = [0] * (n + 1)
    for i in range(1, n + 1):
        phi[i] += i
        for j in range(i * 2, n + 1, i):
            phi[j] -= phi[i]
        for j in range(i, n + 1, i):
            divs[j] += 1
    return (n - phi[n] - divs[n] + 1)


if __name__ == '__main__':
    N = 42
    print(count(N))

# Expected output:
23
# sum of all differences between maximum and minimum of increasing subarrays | function to calculate and return the sum of differences of maximum and minimum of strictly increasing subarrays ; stores the sum ; traverse the array ; if last element of the increasing sub - array is found ; update sum ; if the last element of the array is reached ; update sum ; return the sum ; 
def sum_of_differences(arr, N):
    sum = 0
    i = 0
    while (i < N - 1):
        if arr[i] < arr[i + 1]:
            flag = 0
            for j in range(i + 1, N - 1):
                if arr[j] >= arr[j + 1]:
                    sum += (arr[j] - arr[i])
                    i = j
                    flag = 1
                    break
            if flag == 0 and arr[i] < arr[N - 1]:
                sum += (arr[N - 1] - arr[i])
                break
        i += 1
    return sum


arr = [6, 1, 2, 5, 3, 4]
N = len(arr)
print(sum_of_differences(arr, N))

# Expected output:
5
# minimum size binary string required such that probability of deleting two 1 's at random is 1/x | python3 implementation of the above approach ; function returns the minimum size of the string ; from formula ; left limit of r ; right limit of r ; smallest integer in the valid range ; 

from math import sqrt


def MinimumString(x):
    b = 1
    left_lim = sqrt(x) + 1.0
    right_lim = sqrt(x) + 2.0
    for i in range(int(left_lim), int(right_lim) + 1):
        if (i > left_lim and i < right_lim):
            r = i
            break
    return b + r


if __name__ == '__main__':
    X = 2
    print(MinimumString(X))

# Expected output:
4
# minimum number of squares whose sum equals to a given number n | set | python3 program for the above approach ; function that returns true if n is a perfect square ; function that returns true check if n is sum of three squares ; factor out the powers of 4 ; n is not of the form 4 ^ a * ( 8 b + 7 ) ; function that finds the minimum number of square whose sum is n ; if n is perfect square ; if n is sum of 2 perfect squares ; if n is sum of 3 perfect squares ; otherwise , n is the sum of 4 perfect squares ; 

from math import sqrt, floor, ceil


def isPerfectSquare(N):
    floorSqrt = floor(sqrt(N))
    return (N == floorSqrt * floorSqrt)


def legendreFunction(N):
    while (N % 4 == 0):
        N //= 4
    if (N % 8 != 7):
        return True
    else:
        return False


def minSquares(N):
    if (isPerfectSquare(N)):
        return 1
    for i in range(N):
        if i * i < N:
            break
        if (isPerfectSquare(N - i * i)):
            return 2
    if (legendreFunction(N)):
        return 3
    return 4


if __name__ == '__main__':
    N = 123
    print(minSquares(N))

# Expected output:
3
# check if n leaves only distinct remainders on division by all values up to k | function to check and return if all remainders are distinct ; stores the remainder ; calculate the remainder ; if remainder already occurred ; insert into the set ; 
def is_distinct(n, k):
    s = set()
    for i in range(1, k + 1):
        tmp = n % i
        if (tmp in s):
            return False
        s .add(tmp)
    return True


if __name__ == '__main__':
    N = 5
    K = 3
    if (is_distinct(N, K)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# count of multiplicative partitions of n | function to return number of ways of factoring n with all factors greater than 1 ; variable to store number of ways of factoring n with all factors greater than 1 ; 
def getDivisors(min, n):
    total = 0
    for i in range(min, n):
        if (n % i == 0 and n // i >= i):
            total += 1
            if (n // i > i):
                total += getDivisors(i, n // i)
    return total


if __name__ == '__main__':
    n = 30
    print(1 + getDivisors(2, n))

# Expected output:
5
# find last 2 survivors in n persons standing in a circle after killing next to immediate neighbour | node for a linked list ; function to find the last 2 survivors ; total is the count of alive people ; initiating the list of n people ; total != 2 is terminating condition because at last only two - person will remain alive ; de represent next person to be deleted or killed ; last two person to survive ( in any order ) ; 

class newNode:
    def __init__(self, val):
        self .val = val
        self .next = None


def getLastTwoPerson(n):
    total = n
    head = newNode(1)
    temp = head
    for i in range(2, n + 1, 1):
        temp .next = newNode(i)
        temp = temp .next
    temp .next = head
    temp = head
    de = None
    while (total != 2):
        de = temp .next .next
        temp .next .next = temp .next .next .next
        temp = temp .next
        del de
        total -= 1
    print(temp .val, temp .next .val)


if __name__ == '__main__':
    n = 2
    getLastTwoPerson(n)

# Expected output:
1 2
# philaland coin | tcs mockvita 2020 | python3 implementation to find the minimum number of denominations required for any number ; function to find the minimum number of denomminations required ; 

from math import log2, floor


def findMinDenomin(n):
    return log2(n) + 1


if __name__ == '__main__':
    n = 10
    print(floor(findMinDenomin(n)))

# Expected output:
4
# content of a polynomial | python3 implementation to find the content of the polynomial ; function to find the content of the polynomial ; loop to iterate over the elements of the array ; __gcd ( a , b ) is a inbuilt function for greatest common divisor ; 

from math import gcd


def findContent(arr, n):
    content = arr[0]
    for i in range(1, n):
        content = gcd(content, arr[i])
    return content


if __name__ == '__main__':
    n = 3
    arr = [9, 6, 12]
    print(findContent(arr, n))

# Expected output:
3
# check if the given array is same as its inverse permutation | function to check if the inverse permutation of the given array is same as the original array ; stores the inverse permutation ; generate the inverse permutation ; check if the inverse permutation is same as the given array ; 
def inverseEqual(arr, n):
    brr = [0] * n
    for i in range(n):
        present_index = arr[i] - 1
        brr[present_index] = i + 1
    for i in range(n):
        if arr[i] != brr[i]:
            print("NO")
            return
    print("YES")


n = 4
arr = [1, 4, 3, 2]
inverseEqual(arr, n)

# Expected output:
YES
# linear congruence method for generating pseudo random numbers | function to generate random numbers ; initialize the seed state ; traverse to generate required numbers of random numbers ; follow the linear congruential method ; 
def linearCongruentialMethod(Xo, m, a, c, randomNums, noOfRandomNums):
    randomNums[0] = Xo
    for i in range(1, noOfRandomNums):
        randomNums[i] = ((randomNums[i - 1] * a) + c) % m


if __name__ == '__main__':
    Xo = 5
    m = 7
    a = 3
    c = 3
    noOfRandomNums = 10
    randomNums = [0] * (noOfRandomNums)
    linearCongruentialMethod(Xo, m, a, c, randomNums, noOfRandomNums)
    for i in randomNums:
        print(i, end=" ")

# Expected output:
5 4 1 6 0 3 5 4 1 6
# multiplicative congruence method for generating pseudo random numbers | function to generate random numbers ; initialize the seed state ; traverse to generate required numbers of random numbers ; follow the linear congruential method ; 
def multiplicativeCongruentialMethod(Xo, m, a, randomNums, noOfRandomNums):
    randomNums[0] = Xo
    for i in range(1, noOfRandomNums):
        randomNums[i] = (randomNums[i - 1] * a) % m


if __name__ == '__main__':
    Xo = 3
    m = 15
    a = 7
    noOfRandomNums = 10
    randomNums = [0] * (noOfRandomNums)
    multiplicativeCongruentialMethod(Xo, m, a, randomNums, noOfRandomNums)
    for i in randomNums:
        print(i, end=" ")

# Expected output:
3 6 12 9 3 6 12 9 3 6
# product of divisors of a number from a given list of its prime factors | python3 program to implement the above approach ; function to calculate ( a ^ b ) % m ; function to calculate and return the product of divisors ; stores the frequencies of prime divisors ; iterate over the prime divisors ; update the product ; update the count of divisors ; 

from collections import defaultdict
MOD = 1000000007


def power(a, b, m):
    a %= m
    res = 1
    while (b > 0):
        if (b & 1):
            res = ((res % m) * (a % m)) % m
        a = ((a % m) * (a % m)) % m
        b >>= 1
    return res % m


def productOfDivisors(p, n):
    prime = defaultdict(int)
    for i in range(n):
        prime[p[i]] += 1
    product, d = 1, 1
    for itr in prime .keys():
        val = (power(itr, (prime[itr]) * (prime[itr] + 1) // 2, MOD))
        product = (
            power(
                product,
                prime[itr] +
                1,
                MOD) *
            power(
                val,
                d,
                MOD) %
            MOD)
        d = (d * (prime[itr] + 1)) % (MOD - 1)
    return product


if __name__ == "__main__":
    arr = [11, 11]
    n = len(arr)
    print(productOfDivisors(arr, n))

# Expected output:
1331
# print all proper fractions with denominators less than equal to n | function to print all proper functions ; if the numerator and denominator are coprime ; 
def __gcd(a, b):
    if b == 0:
        return a
    else:
        return __gcd(b, a % b)


def printfractions(n):
    for i in range(1, n):
        for j in range(i + 1, n + 1):
            if __gcd(i, j) == 1:
                a = str(i)
                b = str(j)
                print(a + '/' + b, end=", ")


if __name__ == '__main__':
    n = 3
    printfractions(n)

# Expected output:
1/2, 1/3, 2/3,
# maximum number of objects that can be created as per given conditions | function for finding the maximum number of objects from n type - 1 and m type - 2 items ; storing minimum of n and m ; storing maximum number of objects from given items ; 
def numberOfObjects(N, M):
    initial = min(N, M)
    final = (N + M) // 3
    return min(initial, final)


if __name__ == '__main__':
    N = 8
    M = 7
    print(numberOfObjects(N, M))

# Expected output:
5
# square root of a number by repeated subtraction method | function to return the square root of the given number ; subtract n - th odd number ; return the result ; 
def SquareRoot(num):
    count = 0
    for n in range(1, num + 1, 2):
        num = num - n
        count = count + 1
        if (num == 0):
            break
    return count


N = 81
print(SquareRoot(N))

# Expected output:
9
# maximize count of distinct elements possible in an array from the given operation | function to find the gcd of two numbers ; function to calculate and return the count of maximum possible distinct elements in the array ; find the maximum element ; base case ; finding the gcd of first two element ; calculate gcd of the array ; return the total count of distinct elements ; 
def gcd(x, y):
    if (x == 0):
        return y
    return gcd(y % x, x)


def findDistinct(arr, n):
    maximum = max(arr)
    if (n == 1):
        return 1
    if (n == 2):
        return (maximum // gcd(arr[0], arr[1]))
    k = gcd(arr[0], arr[1])
    for i in range(2, n):
        k = gcd(k, arr[i])
    return (maximum // k)


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

# Expected output:
5
# find indices of all local maxima and local minima in an array | function to find all the local maxima and minima in the given array arr [ ] ; empty lists to store points of local maxima and minima ; checking whether the first point is local maxima or minima or neither ; iterating over all points to check local maxima and local minima ; condition for local minima ; condition for local maxima ; checking whether the last point is local maxima or minima or neither ; print all the local maxima and local minima indexes stored ; 
def findLocalMaximaMinima(n, arr):
    mx = []
    mn = []
    if (arr[0] > arr[1]):
        mx .append(0)
    elif (arr[0] < arr[1]):
        mn .append(0)
    for i in range(1, n - 1):
        if (arr[i - 1] > arr[i] < arr[i + 1]):
            mn .append(i)
        elif (arr[i - 1] < arr[i] > arr[i + 1]):
            mx .append(i)
    if (arr[-1] > arr[-2]):
        mx .append(n - 1)
    elif (arr[-1] < arr[-2]):
        mn .append(n - 1)
    if (len(mx) > 0):
        print("Points of Local maxima are : ", end='')
        print(*mx)
    else:
        print("There are no points of Local maxima.")
    if (len(mn) > 0):
        print("Points of Local minima are : ", end='')
        print(*mn)
    else:
        print("There are no points of Local minima.")


if __name__ == '__main__':
    N = 9
    arr = [10, 20, 15, 14, 13, 25, 5, 4, 3]
    findLocalMaximaMinima(N, arr)

# Expected output:
Points of Local maxima are : 1 5
Points of Local minima are : 0 4 8
# smallest n digit number with none of its digits as its divisor | function to calculate power ; function to check if the n - digit number satisfies the given condition or not ; getting the last digit ; every number is divisible by 1 and dividing a number by 0 isn 't possible. thus  numbers with 0 as a digit  must be discarded. ; if any digit divides the number , return false ; if no digit divides the number , return true ; ; function to find the smallest number not divisible by any of its digits . ; get the lower range of n digit number ; get the high range of n digit number ; check all the n - digit numbers ; if the first number to satify the constraints is found print it , set the flag value and break out of the loop . ; if no such digit found , return - 1 as per problem statement ; 
def power(a, b):
    if (b == 0):
        return 1
    if (b == 1):
        return a
    tmp = power(a, b // 2)
    result = tmp * tmp
    if (b % 2 == 1):
        result *= a
    return result


def check(n):
    temp = n
    while (temp > 0):
        last_digit = temp % 10
        if (last_digit == 0 or last_digit == 1):
            return False
        if (n % last_digit == 0):
            return False
        temp = temp // 10
    return True


def solve(n):
    L = power(10, n - 1)
    R = power(10, n) - 1
    flag = 0
    for i in range(L, R + 1):
        answer = check(i)
        if (answer):
            print(i)
            flag += 1
            break
    if (flag == 0):
        print(-1)


if __name__ == "__main__":
    N = 4
    solve(N)

# Expected output:
2227