giulio98/xlcost-single-prompt huggingface dataset:
# nth subset of the sequence consisting of powers of k in increasing order of their sum | python3 program to print subset at the nth position ordered by the sum of the elements ; function to print the elements of the subset at pos n ; initialize count = 0 and x = 0 ; create a vector for storing the elements of subsets ; doing until all the set bits of n are used ; this part is executed only when the last bit is set ; right shift the bit by one position ; increasing the count each time by one ; printing the values os elements ; 

import math


def printsubset(n, k):
    count = 0
    x = 0
    vec = []
    while (n > 0):
        x = n & 1
        if (x):
            vec .append(pow(k, count))
        n = n >> 1
        count += 1
    for item in vec:
        print(item, end=" ")


n = 7
k = 4
printsubset(n, k)

# Expected output:
1 4 16
# minimum digits to be removed to make either all digits or alternating digits same | function to find longest possible subsequence of s beginning with x and y ; iterate over the string ; increment count ; swap the positions ; return the result ; function that finds all the possible pairs ; update count ; return the answer ; 
def solve(s, x, y):
    res = 0
    for c in s:
        if (ord(c) - ord('0') == x):
            res += 1
            x, y = y, x
    if (x != y and res % 2 == 1):
        res -= 1
    return res


def find_min(s):
    count = 0
    for i in range(10):
        for j in range(10):
            count = max(count, solve(s, i, j))
    return count


s = "100120013"
n = len(s)
answer = find_min(s)
print(n - answer)

# Expected output:
5
# count total set bits in all numbers from range l to r | function to count set bits in x ; base case ; recursive call ; function that returns count of set bits present in all numbers from 1 to n ; initialize the result ; return the setbit count ; 
def countSetBitsUtil(x):
    if (x < 1):
        return 0
    if (x % 2 == 0):
        return 0
    else:
        return 1 + (countSetBitsUtil(x / 2))


def countSetBits(L, R):
    bitCount = 0
    for i in range(L, R + 1):
        bitCount += countSetBitsUtil(i)
    return bitCount


if __name__ == '__main__':
    L = 3
    R = 5
    print("Total set bit count is ", countSetBits(L, R))

# Expected output:
Total set bit count is  5
# possible values of q such that , for any value of r , their product is equal to x times their sum | function to find all possible values of q ; vector initialization to store all numbers satisfying the given condition ; iterate for all the values of x ; check if condition satisfied then push the number ; possible value of q ; print all the numbers ; 
def values_of_Q(X):
    val_Q = []
    for i in range(1, X + 1):
        if ((((X + i) * X)) % i == 0):
            val_Q .append(X + i)
    print(len(val_Q))
    for i in range(len(val_Q)):
        print(val_Q[i], end=" ")


X = 3
values_of_Q(X)

# Expected output:
2
4 6
# program to find greatest common divisor ( gcd ) of n strings | function that finds gcd of 2 strings ; if str1 length is less than that of str2 then recur with gcd ( str2 , str1 ) ; if str1 is not the concatenation of str2 ; gcd string is found ; cut off the common prefix part of str1 & then recur ; function to find gcd of array of strings ; return the gcd of strings ; 
def gcd(str1, str2):
    if (len(str1) < len(str2)):
        return gcd(str2, str1)
    elif (not str1 .startswith(str2)):
        return ""
    elif (len(str2) == 0):
        return str1
    else:
        return gcd(str1[len(str2):], str2)


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


arr = ["GFGGFG", "GFGGFG", "GFGGFGGFGGFG"]
n = len(arr)
print(findGCD(arr, n))

# Expected output:
GFGGFG
# check whether the given matrix is balanced or not | define the size of the matrix ; function to check given matrix balanced or unbalanced ; flag for check matrix is balanced or unbalanced ; iterate row until condition is true ; iterate cols until condition is true ; check for corner edge elements ; check for border elements ; check for the middle ones ; return balanced or not ; 

N = 4
M = 4


def balancedMatrix(mat):
    is_balanced = True
    i = 0
    while i < N and is_balanced:
        j = 0
        while j < N and is_balanced:
            if ((i == 0 or i == N - 1) and (j == 0 or j == M - 1)):
                if mat[i][j] >= 2:
                    isbalanced = False
            elif (i == 0 or i == N - 1 or j == 0 or j == M - 1):
                if mat[i][j] >= 3:
                    is_balanced = False
            else:
                if mat[i][j] >= 4:
                    is_balanced = False
            j += 1
        i += 1
    if is_balanced:
        return "Balanced"
    else:
        return "Unbalanced"


mat = [[1, 2, 3, 4], [3, 5, 2, 6], [5, 3, 6, 1], [9, 5, 6, 0]]
print(balancedMatrix(mat))

# Expected output:
Unbalanced
# convert unix timestamp to dd / mm / yyyy hh : mm : ss format | function to convert unix time to human readable format ; save the time in human readable format ; number of days in month in normal year ; calculate total days unix time t ; calculating current year ; updating extradays because it will give days till previous day and we have include current day ; calculating month and date ; current month ; calculating hh : mm : yyyy ; return the time ; 
def unixTimeToHumanReadable(seconds):
    ans = ""
    daysOfMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    (currYear, daysTillNow, extraTime, extraDays, index, date, month,
     hours, minutes, secondss, flag) = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
    daysTillNow = seconds // (24 * 60 * 60)
    extraTime = seconds % (24 * 60 * 60)
    currYear = 1970
    while (daysTillNow >= 365):
        if (currYear %
            400 == 0 or (currYear %
                         4 == 0 and currYear %
                         100 != 0)):
            daysTillNow -= 366
        else:
            daysTillNow -= 365
        currYear += 1
    extraDays = daysTillNow + 1
    if (currYear % 400 == 0 or (currYear % 4 == 0 and currYear % 100 != 0)):
        flag = 1
    month = 0
    index = 0
    if (flag == 1):
        while (True):
            if (index == 1):
                if (extraDays - 29 < 0):
                    break
                month += 1
                extraDays -= 29
            else:
                if (extraDays - daysOfMonth[index] < 0):
                    break
                month += 1
                extraDays -= daysOfMonth[index]
            index += 1
    else:
        while (True):
            if (extraDays - daysOfMonth[index] < 0):
                break
            month += 1
            extraDays -= daysOfMonth[index]
            index += 1
    if (extraDays > 0):
        month += 1
        date = extraDays
    else:
        if (month == 2 and flag == 1):
            date = 29
        else:
            date = daysOfMonth[month - 1]
    hours = extraTime // 3600
    minutes = (extraTime % 3600) // 60
    secondss = (extraTime % 3600) % 60
    ans += str(date)
    ans += "/"
    ans += str(month)
    ans += "/"
    ans += str(currYear)
    ans += " "
    ans += str(hours)
    ans += ":"
    ans += str(minutes)
    ans += ":"
    ans += str(secondss)
    return ans


if __name__ == "__main__":
    T = 1595497956
    ans = unixTimeToHumanReadable(T)
    print(ans)

# Expected output:
23/7/2020 9:52:36
# maximum area of a rectangle that can be circumscribed about a given rectangle of size lxw | function to find area of rectangle inscribed another rectangle of length l and width w ; area of rectangle ; return the area ; 
def AreaofRectangle(L, W):
    area = (W + L) * (W + L) / 2
    return area


if __name__ == "__main__":
    L = 18
    W = 12
    print(AreaofRectangle(L, W))

# Expected output:
450.0
# minimum number of operations required to reduce n to 0 | python3 program to implement the above approach ; function to count the minimum steps required to reduce n ; base case ; allocate memory for storing intermediate results ; store base values ; stores square root of each number ; compute square root ; use rule 1 to find optimized answer ; check if it perfectly divides n ; use of rule 2 to find the optimized answer ; store computed value ; return answer ; 

import math
import sys


def downToZero(n):
    if (n <= 3):
        return n
    dp = [-1] * (n + 1)
    dp[0] = 0
    dp[1] = 1
    dp[2] = 2
    dp[3] = 3
    for i in range(4, n + 1):
        sqr = (int)(math .sqrt(i))
        best = sys .maxsize
        while (sqr > 1):
            if (i % sqr == 0):
                best = min(best, 1 + dp[sqr])
            sqr -= 1
        best = min(best, 1 + dp[i - 1])
        dp[i] = best
    return dp[n]


if __name__ == "__main__":
    n = 4
    print(downToZero(n))

# Expected output:
3
# minimum number of operations required to reduce n to 0 | function to find the minimum steps required to reduce n ; base case ; return answer based on parity of n ; 
def downToZero(n):
    if (n <= 3):
        return n
    if (n % 2 == 0):
        return 3
    else:
        return 4


if __name__ == '__main__':
    n = 4
    print(downToZero(n))

# Expected output:
3
# minimum count of elements required to obtain the given array by repeated mirror operations | function to find minimum number of elements required to form a [ ] by performing mirroring operation ; initialize k ; odd length array cannot be formed by mirror operation ; check if prefix of length k is palindrome ; check if not a palindrome ; if found to be palindrome ; otherwise ; return the final answer ; 
def minimumrequired(A, N):
    K = N
    while (K > 0):
        if (K % 2) == 1:
            ans = K
            break
        ispalindrome = 1
        for i in range(0, K // 2):
            if (A[i] != A[K - 1 - i]):
                ispalindrome = 0
        if (ispalindrome == 1):
            ans = K // 2
            K = K // 2
        else:
            ans = K
            break
    return ans


A = [1, 2, 2, 1, 1, 2, 2, 1]
N = len(A)
print(minimumrequired(A, N))

# Expected output:
2
# sum of product of all integers upto n with their count of divisors | function to find the sum of the product of all the integers and their positive divisors up to n ; iterate for every number between 1 and n ; find the first multiple of i between 1 and n ; find the last multiple of i between 1 and n ; find the total count of multiple of in [ 1 , n ] ; compute the contribution of i using the formula ; add the contribution of i to the answer ; return the result ; 
def sumOfFactors(N):
    ans = 0
    for i in range(1, N + 1):
        first = i
        last = (N // i) * i
        factors = (last - first) // i + 1
        totalContribution = (((factors * (factors + 1)) // 2) * i)
        ans += totalContribution
    return ans


N = 3
print(sumOfFactors(N))

# Expected output:
11
# find a number m < n such that difference between their xor and and is maximum | function to return m < n such that n ^ m - n & m is maximum ; initialize variables ; iterate for all values < n ; find the difference between bitwise xor and and ; check if new difference is greater than previous maximum ; update variables ; return the answer ; 
def getMaxDifference(N):
    M = -1
    maxDiff = 0
    for i in range(N):
        diff = (N ^ i) - (N & i)
        if (diff >= maxDiff):
            maxDiff = diff
            M = i
    return M


if __name__ == '__main__':
    N = 6
    print(getMaxDifference(N))

# Expected output:
1
# find a number m < n such that difference between their xor and and is maximum | python3 program for the above approach ; function to flip all bits of n ; finding most significant bit of n ; calculating required number ; return the answer ; 

import math


def findM(N):
    M = 0
    MSB = int(math .log(N))
    for i in range(MSB):
        if ((N & (1 << i)) == 0):
            M += (1 << i)
    return M


if __name__ == '__main__':
    N = 6
    print(findM(N))

# Expected output:
1
# number of containers that can be filled in the given time | matrix of containers ; function to find the number of containers that will be filled in x seconds ; container on top level ; if container gets filled ; dividing the liquid equally in two halves ; 

cont = [[0 for i in range(1000)]for j in range(1000)]


def num_of_containers(n, x):
    count = 0
    cont[1][1] = x
    for i in range(1, n + 1):
        for j in range(1, i + 1):
            if (cont[i][j] >= 1):
                count += 1
                cont[i + 1][j] += (cont[i][j] - 1) / 2
                cont[i + 1][j + 1] += (cont[i][j] - 1) / 2
    print(count)


n = 3
x = 5
num_of_containers(n, x)

# Expected output:
4
# check whether there exists a triplet ( i , j , k ) such that arr [ i ] < arr [ k ] < arr [ j ] for i < j < k | python3 program for the above approach ; function to check if there exist triplet in the array such that i < j < k and arr [ i ] < arr [ k ] < arr [ j ] ; initialize the heights of h1 and h3 to int_max and int_min respectively ; store the current element as h1 ; if the element at top of stack is less than the current element then pop the stack top and keep updating the value of h3 ; push the current element on the stack ; if current element is less than h3 , then we found such triplet and return true ; no triplet found , hence return false ; 

import sys


def findTriplet(arr):
    n = len(arr)
    st = []
    h3 = -sys .maxsize - 1
    h1 = sys .maxsize
    for i in range(n - 1, -1, -1):
        h1 = arr[i]
        while (len(st) > 0 and st[-1] < arr[i]):
            h3 = st[-1]
            del st[-1]
        st .append(arr[i])
        if (h1 < h3):
            return True
    return False


if __name__ == '__main__':
    arr = [4, 7, 5, 6]
    if (findTriplet(arr)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# minimum number of distinct elements after removing m items | set 2 | function to return minimum distinct character after m removals ; count the occurences of number and store in count ; count the occurences of the frequencies ; take answer as total unique numbers and remove the frequency and subtract the answer ; remove the minimum number of times ; return the answer ; 
def distinctNumbers(arr, m, n):
    count = {}
    for i in range(n):
        count[arr[i]] = count .get(arr[i], 0) + 1
    fre_arr = [0] * (n + 1)
    for it in count:
        fre_arr[count[it]] += 1
    ans = len(count)
    for i in range(1, n + 1):
        temp = fre_arr[i]
        if (temp == 0):
            continue
        t = min(temp, m // i)
        ans -= t
        m -= i * t
    return ans


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

# Expected output:
3
# find minimum moves to bring all elements in one cell of a matrix | python3 implementation to find the minimum number of moves to bring all non - zero element in one cell of the matrix ; function to find the minimum number of moves to bring all elements in one cell of matrix ; moves variable to store the sum of number of moves ; loop to count the number of the moves ; condition to check that the current cell is a non - zero element ; 

M = 4
N = 5


def no_of_moves(Matrix, x, y):
    moves = 0
    for i in range(M):
        for j in range(N):
            if (Matrix[i][j] != 0):
                moves += abs(x - i)
                moves += abs(y - j)
    print(moves)


if __name__ == '__main__':
    x = 3
    y = 2
    Matrix = [[1, 0, 1, 1, 0], [0, 1, 1, 0, 1],
              [0, 0, 1, 1, 0], [1, 1, 1, 0, 0]]
    num = 1
    no_of_moves(Matrix, x, y)

# Expected output:
27
# check if all array elements can be removed by the given operations | function to check if it is possible to remove all array elements ; condition if we can remove all elements from the array ; 
def removeAll(arr, n):
    if arr[0] < arr[n - 1]:
        print("YES")
    else:
        print("NO")


arr = [10, 4, 7, 1, 3, 6]
removeAll(arr, len(arr))

# Expected output:
NO
# count substring of binary string such that each character belongs to a palindrome of size greater than 1 | function to find the substrings in binary string such that every character belongs to a palindrome ; total substrings ; loop to store the count of continuous characters in the given string ; subtract non special strings from answer ; 
def countSubstrings(s):
    n = len(s)
    answer = (n * (n - 1)) // 2
    cnt = 1
    v = []
    for i in range(1, n):
        if (s[i] == s[i - 1]):
            cnt += 1
        else:
            v .append(cnt)
            cnt = 1
    if (cnt > 0):
        v .append(cnt)
    for i in range(len(v) - 1):
        answer -= (v[i] + v[i + 1] - 1)
    return answer


if __name__ == '__main__':
    s = "00111"
    print(countSubstrings(s))

# Expected output:
6
# minimum minutes needed to make the time palindromic | function to get the required minutes ; storing hour and minute value in integral form ; keep iterating till first digit hour becomes equal to second digit of minute and second digit of hour becomes equal to first digit of minute ; if mins is 60 , increase hour , and reinitilialized to 0 ; if hours is 60 , reinitialized to 0 ; return the required time ; 
def get_palindrome_time(str):
    hh = ((ord(str[0]) - 48) * 10 + (ord(str[1]) - 48))
    mm = ((ord(str[3]) - 48) * 10 + (ord(str[4]) - 48))
    requiredTime = 0
    while (hh % 10 != mm // 10 or hh // 10 != mm % 10):
        mm += 1
        if (mm == 60):
            mm = 0
            hh += 1
        if (hh == 24):
            hh = 0
        requiredTime += 1
    return requiredTime


if __name__ == "__main__":
    str = "05:39"
    print(get_palindrome_time(str))

# Expected output:
11
# maximum sum of values in a given range of an array for q queries when shuffling is allowed | function to find the maximum sum of all subarrays ; initialize maxsum and prefixarray ; find the frequency using prefix array ; perform prefix sum ; sort both arrays to get a greedy result ; finally multiply largest frequency with largest array element . ; return the answer ; 
def maximumSubarraySum(a, n, subarrays):
    maxsum = 0
    prefixArray = [0] * n
    for i in range(len(subarrays)):
        prefixArray[subarrays[i][0] - 1] += 1
        prefixArray[subarrays[i][1]] -= 1
    for i in range(1, n):
        prefixArray[i] += prefixArray[i - 1]
    prefixArray .sort()
    prefixArray .reverse()
    a .sort()
    a .reverse()
    for i in range(n):
        maxsum += a[i] * prefixArray[i]
    return maxsum


n = 6
a = [4, 1, 2, 1, 9, 2]
subarrays = [[1, 2], [1, 3], [1, 4], [3, 4]]
print(maximumSubarraySum(a, n, subarrays))

# Expected output:
49
# maximum profit such that total stolen value is less than k to get bonus | function to find the maximum profit from the given values ; iterating over every possible permutation ; 
def next_permutation(p):
    for a in range(len(p) - 2, -1, -1):
        if p[a] < p[a + 1]:
            b = len(p) - 1
            while True:
                if p[b] > p[a]:
                    t = p[a]
                    p[a] = p[b]
                    p[b] = t
                    a += 1
                    b = len(p) - 1
                    while a < b:
                        t = p[a]
                        p[a] = p[b]
                        p[b] = t
                        a += 1
                        b -= 1
                    return True
                b -= 1
    return False


def maxProfit(value, N, K):
    value .sort()
    maxval = value[N - 1]
    maxProfit = 0
    while True:
        curr_val = 0
        for i in range(N):
            curr_val += value[i]
            if (curr_val <= K):
                maxProfit = max(curr_val + maxval * (i + 1), maxProfit)
        if not next_permutation(value):
            break
    return maxProfit


N, K = 4, 6
values = [5, 2, 7, 3]
print(maxProfit(values, N, K))

# Expected output:
19
# min operations to reduce n by multiplying by any number or taking square root | python3 program for the above approach ; function to reduce n to its minimum possible value by the given operations ; keep replacing n until is an integer ; keep replacing n until n is divisible by i * i ; print the answer ; 

import math


def MinValue(n):
    while (int(math .sqrt(n)) == math .sqrt(n) and n > 1):
        n = math .sqrt(n)
    for i in range(int(math .sqrt(n)), 1, -1):
        while (n % (i * i) == 0):
            n /= i
    print(n)


n = 20
MinValue(n)

# Expected output:
10.0
# count of ways to split given string into two non | function to check whether the substring from l to r is palindrome or not ; if characters at l and r differ ; not a palindrome ; if the string is a palindrome ; function to count and return the number of possible splits ; stores the count of splits ; check if the two substrings after the split are palindromic or not ; if both are palindromes ; print the final count ; 
def isPalindrome(l, r, s):
    while (l <= r):
        if (s[l] != s[r]):
            return bool(False)
        l += 1
        r -= 1
    return bool(True)


def numWays(s):
    n = len(s)
    ans = 0
    for i in range(n - 1):
        if (isPalindrome(0, i, s) and isPalindrome(i + 1, n - 1, s)):
            ans += 1
    return ans


S = "aaaaa"
print(numWays(S))

# Expected output:
4
# final direction after visiting every cell of matrix starting from ( 0 , 0 ) | function to find the direction when stopped moving ; 
def findDirection(n, m):
    if (n > m):
        if (m % 2 == 0):
            print("Up")
        else:
            print("Down")
    else:
        if (n % 2 == 0):
            print("Left")
        else:
            print("Right")


n = 3
m = 3
findDirection(n, m)

# Expected output:
Right
# maximize the sum of modulus with every array element | function to return the maximum sum of modulus with every array element ; sum of array elements ; return the answer ; 
def maxModulosum(a, n):
    sum1 = 0
    for i in range(0, n):
        sum1 += a[i]
    return sum1 - n


a = [3, 4, 6]
n = len(a)
print(maxModulosum(a, n))

# Expected output:
10
# minimum jumps required to group all 1 s together in a given binary string | function to get the minimum jump value ; store all indices of ones ; populating one 's indices ; calculate median ; jumps required for 1 's  to the left of median ; jumps required for 1 's  to the right of median ; return the final answer ; 
def getMinJumps(s):
    ones = []
    jumps, median, ind = 0, 0, 0
    for i in range(len(s)):
        if (s[i] == '1'):
            ones .append(i)
    if (len(ones) == 0):
        return jumps
    median = ones[len(ones) // 2]
    ind = median
    for i in range(ind, -1, -1):
        if (s[i] == '1'):
            jumps += ind - i
            ind -= 1
    ind = median
    for i in range(ind, len(s)):
        if (s[i] == '1'):
            jumps += i - ind
            ind += 1
    return jumps


if __name__ == '__main__':
    s = "00100000010011"
    print(getMinJumps(s))

# Expected output:
10