giulio98/xlcost-single-prompt huggingface dataset:
# sum of all n digit palindrome numbers | python program for the above approach ; function to check palindrome ; function to calculate the sum of n - digit palindrome ; run a loop to check all possible palindrome ; if palindrome append sum ; 

import math


def isPalindrome(s):
    left = 0
    right = len(s) - 1
    while (left <= right):
        if (s[left] != s[right]):
            return False
        left = left + 1
        right = right - 1
    return True


def getSum(n):
    start = int(math .pow(10, n - 1))
    end = int(math .pow(10, n)) - 1
    sum = 0
    for i in range(start, end + 1):
        s = str(i)
        if (isPalindrome(s)):
            sum = sum + i
    return sum


n = 1
ans = getSum(n)
print(ans)

# Expected output:
45
# sum of all n digit palindrome numbers | function to calculate sum of n digit number ; corner case ; using above approach ; 
def getSum(n):
    sum = 0
    if (n == 1):
        sum = 45.0
    else:
        sum = (99.0 / 2.0) * pow(10, n - 1) * pow(10, (n - 1) / 2)
    return sum


if __name__ == '__main__':
    n = 3
    ans = int(getSum(n))
    print(ans)

# Expected output:
49500
# count number of pairs ( i , j ) such that arr [ i ] * arr [ j ] = arr [ i ] + arr [ j ] | function to return the count of pairs ( i , j ) such that arr [ i ] * arr [ j ] = arr [ i ] + arr [ j ] ; increment count if condition satisfy ; return count of pairs ; 
def countPairs(arr, n):
    count = 0
    for i in range(n - 1):
        for j in range(i + 1, n):
            if (arr[i] * arr[j] == arr[i] + arr[j]):
                count += 1
    return count


if __name__ == "__main__":
    arr = [2, 0, 3, 2, 0]
    n = len(arr)
    print(countPairs(arr, n))

# Expected output:
2
# count number of pairs ( i , j ) such that arr [ i ] * arr [ j ] = arr [ i ] + arr [ j ] | function to return the count of pairs ( i , j ) such that arr [ i ] * arr [ j ] = arr [ i ] + arr [ j ] ; count number of 0 ' s ▁ and ▁ 2' s in the array ; total pairs due to occurrence of 0 's  ; total pairs due to occurrence of 2 's  ; return count of all pairs ; 
def countPairs(arr, n):
    countZero = 0
    countTwo = 0
    for i in range(n):
        if (arr[i] == 0):
            countZero += 1
        elif (arr[i] == 2):
            countTwo += 1
    pair0 = (countZero * (countZero - 1)) // 2
    pair2 = (countTwo * (countTwo - 1)) // 2
    return pair0 + pair2


if __name__ == "__main__":
    arr = [2, 0, 3, 2, 0]
    n = len(arr)
    print(countPairs(arr, n))

# Expected output:
2
# number of subsequences with positive product | python 3 implementation of the approach ; function to return the count of all the subsequences with positive product ; to store the count of positive elements in the array ; to store the count of negative elements in the array ; if the current element is positive ; if the current element is negative ; for all the positive elements of the array ; for all the negative elements of the array ; for the empty subsequence ; 

import math


def cntSubSeq(arr, n):
    pos_count = 0
    neg_count = 0
    for i in range(n):
        if (arr[i] > 0):
            pos_count += 1
        if (arr[i] < 0):
            neg_count += 1
    result = int(math .pow(2, pos_count))
    if (neg_count > 0):
        result *= int(math .pow(2, neg_count - 1))
    result -= 1
    return result


arr = [2, -3, -1, 4]
n = len(arr)
print(cntSubSeq(arr, n))

# Expected output:
7
# smallest number dividing minimum number of elements in the array | set 2 | function to return the smallest number that divides minimum number of elements in the given array ; m stores the maximum in the array ; frequency array ; sieve ; incrementing j ; if no multiples of j are in the array ; 
def findMin(arr, n):
    m = 0
    for i in range(n):
        m = max(m, arr[i])
    freq = [0] * (m + 2)
    for i in range(n):
        freq[arr[i]] += 1
    for i in range(1, m + 2):
        j = i
        cnt = 0
        while (j <= m):
            cnt += freq[j]
            j += i
        if (not cnt):
            return i
    return m + 1


arr = [2, 12, 6]
n = len(arr)
print(findMin(arr, n))

# Expected output:
5
# smallest number dividing minimum number of elements in the array | function to return the smallest number that divides minimum number of elements ; m stores the maximum in the array ; frequency table ; loop to factorize ; sqrt factorization of the numbers ; finding the smallest number with zero multiples ; 
def findMin(arr, n):
    m = 0
    for i in range(n):
        m = max(m, arr[i])
    cnt = [0] * (m + 2)
    for i in range(n):
        j = 1
        while j * j <= arr[i]:
            if (arr[i] % j == 0):
                if (j * j == arr[i]):
                    cnt[j] += 1
                else:
                    cnt[j] += 1
                    cnt[arr[i] // j] += 1
            j += 1
    for i in range(1, m + 2):
        if (cnt[i] == 0):
            return i
    return -1


arr = [2, 12, 6]
n = len(arr)
print(findMin(arr, n))

# Expected output:
5
# remove two consecutive integers from 1 to n to make sum equal to s | function to find the numbers to be removed ; typecast appropriately so that answer is float ; return the obtained result ; convert i to integer ; if i is an integer is 0 then answer is yes ; 
def findNumber(N, S):
    i = (((N) * (N + 1)) / 4) - ((S + 1) / 2)
    return i


def check(N, S):
    i = findNumber(N, S)
    integerI = int(i)
    if (i - integerI == 0):
        print("Yes:", integerI, ",", integerI + 1)
    else:
        print("No")


if __name__ == "__main__":
    N = 4
    S = 3
    check(N, S)
    N = 5
    S = 3
    check(N, S)

# Expected output:
Yes: 3 , 4
No
# remove all the prime numbers from the given array | python3 implementation of the approach ; function for sieve of eratosthenes ; function to pr the elements of the array ; function to remove all the prime numbers ; generate primes ; traverse the array ; if the current element is prime ; shift all the elements on the right of it to the left ; decrease the loop counter by 1 to check the shifted element ; decrease the length ; pr the updated array ; 

sz = 10 ** 5
isPrime = [True for i in range(sz + 1)]


def sieve():
    isPrime[0] = isPrime[1] = False
    i = 2
    while i * i < sz:
        if (isPrime[i]):
            for j in range(i * i, sz, i):
                isPrime[j] = False
        i += 1


def prArray(arr, lenn):
    for i in range(lenn):
        print(arr[i], end=" ")


def removePrimes(arr, lenn):
    sieve()
    i = 0
    while i < lenn:
        if (isPrime[arr[i]]):
            for j in range(i, lenn - 1):
                arr[j] = arr[j + 1]
            i -= 1
            lenn -= 1
        i += 1
    prArray(arr, lenn)


if __name__ == '__main__':
    arr = [4, 6, 5, 3, 8, 7, 10, 11, 14, 15]
    lenn = len(arr)
    removePrimes(arr, lenn)

# Expected output:
4 6 8 10 14 15
# remove one element to get minimum or value | function to return the minimized or after removing an element from the array ; base case ; prefix and suffix or array ; computing prefix / suffix or arrays ; to store the final answer ; finding the final answer ; returning the final answer ; 
def minOR(arr, n):
    if (n == 1):
        return 0
    pre = [0] * n
    suf = [0] * n
    pre[0] = arr[0]
    suf[n - 1] = arr[n - 1]
    for i in range(1, n):
        pre[i] = (pre[i - 1] | arr[i])
    for i in range(n - 2, -1, -1):
        suf[i] = (suf[i + 1] | arr[i])
    ans = min(pre[n - 2], suf[1])
    for i in range(1, n - 1):
        ans = min(ans, (pre[i - 1] | suf[i + 1]))
    return ans


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

# Expected output:
3
# check if there exists a prime number which gives y after being repeatedly subtracted from x | function that returns true if any prime number satisfies the given conditions ; no such prime exists ; 
def isPossible(x, y):
    if ((x - y) == 1):
        return False
    return True


x = 100
y = 98
if (isPossible(x, y)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# find number of square of area z which can be built in a matrix having blocked regions | python3 implementation of the approach ; function to calculate the number of square areas of size k * k ; row array and column array to store the lengths of differences between consecutive rows / columns ; fill the conrow vector ; fill the concol vector ; to store the required answer ; every pair of row size and column size would result in an unblocked region ; 

from math import sqrt


def subgrids(N, Z, row, col, r, d):
    conrow = []
    concol = []
    K = int(sqrt(Z))
    conrow .append(row[0] - 0 - 1)
    conrow .append(N + 1 - row[r - 1] - 1)
    for i in range(1, r):
        conrow .append(row[i] - row[i - 1] - 1)
    concol .append(col[0] - 0 - 1)
    concol .append(N + 1 - col[d - 1] - 1)
    for i in range(1, d):
        concol .append(col[i] - col[i - 1] - 1)
    row_size = len(conrow)
    col_size = len(concol)
    answer = 0
    for i in range(row_size):
        for j in range(col_size):
            total = (concol[j] // K) * (conrow[i] // K)
            answer += (total)
    return answer


if __name__ == "__main__":
    N = 8
    Z = 4
    row = [4, 6]
    col = [3, 8]
    r = len(row)
    d = len(col)
    print(subgrids(N, Z, row, col, r, d))

# Expected output:
6
# count of numbers whose sum of increasing powers of digits is equal to the number itself | function to return the count of digits of n ; function to return the sum of increasing powers of n ; to store the required answer ; count of digits in n which will be the power of the last digit ; while there are digits left ; get the last digit ; add the last digit after raising it to the required power ; decrement the power for the previous digit ; remove the last digit ; function to return the count of integers which satisfy the given conditions ; if current element satisfies the given condition ; 
def countDigits(n):
    cnt = 0
    while (n > 0):
        cnt += 1
        n //= 10
    return cnt


def digitPowSum(n):
    sum = 0
    pw = countDigits(n)
    while (n > 0):
        d = n % 10
        sum += pow(d, pw)
        pw -= 1
        n //= 10
    return sum


def countNum(n):
    count = 0
    for i in range(n + 1):
        if (i == digitPowSum(i)):
            count += 1
    return count


n = 200
print(countNum(n))

# Expected output:
13
# print all perfect squares from the given range | function to print all the perfect squares from the given range ; for every element from the range ; if current element is a perfect square ; 
def perfectSquares(l, r):
    for i in range(l, r + 1):
        if (i ** (.5) == int(i ** (.5))):
            print(i, end=" ")


l = 2
r = 24
perfectSquares(l, r)

# Expected output:
4 9 16
# print all perfect squares from the given range | python3 implementation of the approach ; function to print all the perfect squares from the given range ; getting the very first number ; first number 's square ; next number is at the difference of ; while the perfect squares are from the range ; print the perfect square ; get the next perfect square ; next odd number to be added ; 

from math import ceil, sqrt


def perfectSquares(l, r):
    number = ceil(sqrt(l))
    n2 = number * number
    number = (number * 2) + 1
    while ((n2 >= l and n2 <= r)):
        print(n2, end=" ")
        n2 = n2 + number
        number += 2


if __name__ == "__main__":
    l = 2
    r = 24
    perfectSquares(l, r)

# Expected output:
4 9 16
# find the value of n xor 'ed to itself k times | function to return n ^ n ^ ... k times ; find the result ; 
def xorK(n, k):
    res = n
    for i in range(1, k):
        res = (res ^ n)
    return n


n = 123
k = 3
print(xorK(n, k))

# Expected output:
123
# find all the possible remainders when n is divided by all positive integers from 1 to n + 1 | python3 implementation of the approach ; function to find all the distinct remainders when n is divided by all the elements from the range [ 1 , n + 1 ] ; set will be used to store the remainders in order to eliminate duplicates ; find the remainders ; print the contents of the set ; 

from math import ceil, floor, sqrt


def findRemainders(n):
    vc = dict()
    for i in range(1, ceil(sqrt(n)) + 1):
        vc[n // i] = 1
    for i in range(n // ceil(sqrt(n)) - 1, -1, -1):
        vc[i] = 1
    for it in sorted(vc):
        print(it, end=" ")


n = 5
findRemainders(n)

# Expected output:
0 1 2 5
# count of primes below n which can be expressed as the sum of two primes | python3 implementation of the approach ; function for sieve of eratosthenes ; false here indicates that it is not prime ; if prime [ p ] is not changed , then it is a prime ; update all multiples of p , set them to non - prime ; function to return the count of primes less than or equal to n which can be expressed as the sum of two primes ; to store the required count ; if the integer is prime and it can be expressed as the sum of 2 and a prime number ; 

MAX = 100005
prime = [True for i in range(MAX)]


def SieveOfEratosthenes():
    prime[0] = False
    prime[1] = False
    for p in range(MAX):
        if (p * p > MAX):
            break
        if (prime[p]):
            for i in range(2 * p, MAX, p):
                prime[i] = False


def countPrimes(n):
    SieveOfEratosthenes()
    cnt = 0
    for i in range(2, n):
        if (prime[i] and prime[i - 2]):
            cnt += 1
    return cnt


n = 11
print(countPrimes(n))

# Expected output:
2
# print all palindrome dates between the given years | python 3 implementation of the approach ; returns true if given year is valid ; return true if year is a multiple pf 4 and not multiple of 100. or year is multiple of 400. ; returns true if given year is valid or not . ; if year , month and day are not in given range ; handle february month with leap year ; months of april , june , sept and nov must have number of days less than or equal to 30. ; function to print the palindrome dates between the given years ; for every year ; current year as a string ; to store the reverse of year ; get the day and the month ; if the current palindrome date is valid ; 

MAX_VALID_YR = 9999
MIN_VALID_YR = 1800


def isLeap(year):
    return (((year % 4 == 0) and (year % 100 != 0)) or (year % 400 == 0))


def isValidDate(d, m, y):
    if (y > MAX_VALID_YR or y < MIN_VALID_YR):
        return False
    if (m < 1 or m > 12):
        return False
    if (d < 1 or d > 31):
        return False
    if (m == 2):
        if (isLeap(y)):
            return (d <= 29)
        else:
            return (d <= 28)
    if (m == 4 or m == 6 or m == 9 or m == 11):
        return (d <= 30)
    return True


def printPalindromeDates(y1, y2):
    for year in range(y1, y2 + 1, 1):
        str1 = str(year)
        rev = str1
        rev = rev[::-1]
        day = int(rev[0:2])
        month = int(rev[2:4])
        rev += str1
        if (isValidDate(day, month, year)):
            print(rev)


if __name__ == '__main__':
    y1 = 2001
    y2 = 2005
    printPalindromeDates(y1, y2)

# Expected output:
10022001
20022002
# find an integer in the given range that satisfies the given conditions | python3 implementation of the approach ; function that returns true if x contains all distinct digits ; last digit of x ; if current digit has appeared before ; mark the current digit to present ; remove the last digit ; function to return the required value of k ; to store the maximum value for the given expression ; if i contains all distinct digits ; if the value of the expression is also maximum then update k and the expression ; 

import sys
MAX = 10


def distinctDigits(x):
    present = [False for i in range(MAX)]
    while (x > 0):
        digit = x % 10
        if (present[digit]):
            return False
        present[digit] = True
        x = x // 10
    return True


def findK(l, r):
    maxExp = -sys .maxsize - 1
    k = -1
    for i in range(l, r + 1, 1):
        if (distinctDigits(i)):
            exp = (l - i) * (i - r)
            if (exp >= maxExp):
                k = i
                maxExp = exp
    return k


if __name__ == '__main__':
    l = 50
    r = 60
    print(findK(l, r))

# Expected output:
56
# convert decimal to hexa | function to convert decimal no . to hexadecimal number ; map for decimal to hexa , 0 - 9 are straightforward , alphabets a - f used for 10 to 15. ; string to be returned ; check if num is 0 and directly return "0" ; if num > 0 , use normal technique as discussed in other post ; if num < 0 , we need to use the elaborated trick above , lets see this ; store num in a u_int , size of u_it is greater , it will be positive since msb is 0 ; use the same remainder technique . ; 
def Hex(num):
    m = dict .fromkeys(range(16), 0)
    digit = ord('0')
    c = ord('a')
    for i in range(16):
        if (i < 10):
            m[i] = chr(digit)
            digit += 1
        else:
            m[i] = chr(c)
            c += 1
    res = ""
    if (not num):
        return "0"
    if (num > 0):
        while (num):
            res = m[num % 16] + res
            num //= 16
    else:
        n = num + 2 ** 32
        while (n):
            res = m[n % 16] + res
            n //= 16
    return res


if __name__ == "__main__":
    x = 134
    y = -1
    z = -234
    print("Hexa representation for")
    print(x, "is", Hex(x))
    print(y, "is", Hex(y))
    print(z, "is", Hex(z))

# Expected output:
Hexa representation for
134 is 86
-1 is ffffffff
-234 is ffffff16
# find the player who will win the coin game | function to check the wining player ; as discussed in the above approach ; 
def findWinner(n):
    if ((n - 1) % 6 == 0):
        print("Second Player wins the game")
    else:
        print("First Player wins the game")


if __name__ == '__main__':
    n = 7
    findWinner(n)

# Expected output:
Second Player wins the game
# find ways to arrange k green balls among n balls such that exactly i moves is needed to collect all k green balls | python3 implementation of the approach ; to store the factorial and the factorial mod inverse of a number ; function to find ( a ^ m1 ) % mod ; function to find factorial of all the numbers ; function to find the factorial mod inverse of all the numbers ; function to return ncr ; function to find ways to arrange k green balls among n balls such that we need exactly i moves to collect all k green balls ; 

N = 100005
mod = (int)(1e9 + 7)
factorial = [0] * N
modinverse = [0] * N


def power(a, m1):
    if (m1 == 0):
        return 1
    elif (m1 == 1):
        return a
    elif (m1 == 2):
        return (a * a) % mod
    elif (m1 & 1):
        return (a * power(power(a, m1 // 2), 2)) % mod
    else:
        return power(power(a, m1 // 2), 2) % mod


def factorialfun():
    factorial[0] = 1
    for i in range(1, N):
        factorial[i] = (factorial[i - 1] * i) % mod


def modinversefun():
    modinverse[N - 1] = power(factorial[N - 1], mod - 2) % mod
    for i in range(N - 2, -1, -1):
        modinverse[i] = (modinverse[i + 1] * (i + 1)) % mod


def binomial(n, r):
    if (r > n):
        return 0
    a = (factorial[n] * modinverse[n - r]) % mod
    a = (a * modinverse[r]) % mod
    return a


def arrange_balls(n, k):
    factorialfun()
    modinversefun()
    for i in range(1, k + 1):
        print((binomial(n - k + 1, i) * binomial(k - 1, i - 1)) % mod, end=" ")


if __name__ == "__main__":
    n = 5
    k = 3
    arrange_balls(n, k)

# Expected output:
3 6 1
# minimum inversions required so that no two adjacent elements are same | function to return the minimum inversions required so that no two adjacent elements are same ; to store the inversions required to make the array { 1 , 0 , 1 , 0 , 1 , 0 , 1 , ... } and { 0 , 1 , 0 , 1 , 0 , 1 , 0 , ... } respectively ; find all the changes required ; return the required answer ; 
def min_changes(a, n):
    ans_a = 0
    ans_b = 0
    for i in range(n):
        if (i % 2 == 0):
            if (a[i] == 0):
                ans_a += 1
            else:
                ans_b += 1
        else:
            if (a[i] == 0):
                ans_b += 1
            else:
                ans_a += 1
    return min(ans_a, ans_b)


if __name__ == '__main__':
    a = [1, 0, 0, 1, 0, 0, 1, 0]
    n = len(a)
    print(min_changes(a, n))

# Expected output:
3
# sum of all the numbers present at given level in modified pascal ’ s triangle | function to calculate sum ; 
def ans(n):
    if (n == 1):
        print("1", end="")
    else:
        print("0", end="")


if __name__ == "__main__":
    n = 2
    ans(n)

# Expected output:
0
# find if there exists multiple ways to draw line through ( x , y ) to cut rectangle in equal halfs | function that returns true if multiple lines are possible passing through ( x , y ) that divide the given rectangle into two equal parts ; if the point ( x , y ) is the centre of the rectangle ; 
def isPossible(w, h, x, y):
    if (x * 2 == w and y * 2 == h):
        return True
    return False


if __name__ == '__main__':
    w = 1
    h = 2
    x = 1
    y = 2
    if (isPossible(w, h, x, y)):
        print("Yes")
    else:
        print("No")

# Expected output:
No
# minimize the number by changing at most k digits | function to return the minimized number ; total digits in the number ; if the string is empty or there are no operations to perform ; "0" is a valid number ; if the first digit is not already 1 then update it to 1 and decrement k ; while there are operations left and the number can still be updated ; if the current digit is not already 0 then update it to 0 and decrement k ; return the minimised number ; 
def minNum(num, k):
    len_ = len(num)
    if len_ == 0 or k == 0:
        return num
    if len_ == 1:
        return "0"
    if num[0] != '1':
        num = '1' + num[1:]
        k -= 1
    i = 1
    while k > 0 and i < len_:
        if num[i] != '0':
            num = num[:i] + '0' + num[i + 1:]
            k -= 1
        i += 1
    return num


num = "91945"
k = 3
print(minNum(num, k))

# Expected output:
10045
# form n by adding 1 or 2 in minimum number of operations x where x is divisible by m | function to calculate the minimum number of steps required total steps taken is divisible by m and only 1 or 2 steps can be taken at a time ; if m > n ans is - 1 ; else discussed above approach ; 
def minsteps(n, m):
    if (m > n):
        return -1
    else:
        return ((n + 1) // 2 + m - 1) // m * m


n = 17
m = 4
ans = minsteps(n, m)
print(ans)

# Expected output:
12
# sum of the updated array after performing the given operation | utility function to return the sum of the array ; function to return the sum of the modified array ; find the sum of the subarray arr [ i + 1. . . n - 1 ] ; subtract the subarray sum ; return the sum of the modified array ; 
def sumArr(arr, n):
    sum = 0
    for i in range(n):
        sum += arr[i]
    return sum


def sumModArr(arr, n):
    for i in range(n - 1):
        subSum = 0
        for j in range(i + 1, n):
            subSum += arr[j]
        arr[i] -= subSum
    return sumArr(arr, n)


arr = [40, 25, 12, 10]
n = len(arr)
print(sumModArr(arr, n))

# Expected output:
8
# find the minimum possible health of the winning player | python3 implementation of the approach ; function to return the minimum possible health of the last player ; find the gcd of the array elements ; 

from math import gcd


def minHealth(health, n):
    __gcd = 0
    for i in range(n):
        __gcd = gcd(__gcd, health[i])
    return __gcd


if __name__ == "__main__":
    health = [5, 6, 1, 2, 3, 4]
    n = len(health)
    print(minHealth(health, n))

# Expected output:
1