giulio98/xlcost-single-prompt huggingface dataset:
# split an array into minimum number of non | function to split the array into minimum count of subarrays such that each subarray is either non - increasing or non - decreasing ; initialize variable to keep track of current sequence ; stores the required result ; traverse the array , arr [ ] ; if current sequence is neither non - increasing nor non - decreasing ; if previous element is greater ; update current ; if previous element is equal to the current element ; update current ; otherwise ; update current ; if current sequence is in non - decreasing ; i f previous element is less than or equal to the current element ; otherwise ; update current as n and increment answer by 1 ; if current sequence is non - increasing ; if previous element is greater or equal to the current element ; otherwise ; update current as n and increment answer by 1 ; print the answer ; 
def minimumSubarrays(arr, n):
    current = 'N'
    answer = 1
    for i in range(1, n):
        if (current == 'N'):
            if (arr[i] < arr[i - 1]):
                current = 'D'
            elif (arr[i] == arr[i - 1]):
                current = 'N'
            else:
                current = 'I'
        elif (current == 'I'):
            if (arr[i] >= arr[i - 1]):
                current = 'I'
            else:
                current = 'N'
                answer += 1
        else:
            if (arr[i] <= arr[i - 1]):
                current = 'D'
            else:
                current = 'N'
                answer += 1
    print(answer)


if __name__ == '__main__':
    arr = [2, 3, 9, 5, 4, 6, 8]
    n = len(arr)
    minimumSubarrays(arr, n)

# Expected output:
3
# convert a matrix into another matrix of given dimensions | function to construct a matrix of size a * b from the given matrix elements ; initialize a new matrix ; traverse the matrix , mat [ ] [ ] ; update idx ; print the resultant matrix ; 
def ConstMatrix(mat, N, M, A, B):
    if (N * M != A * B):
        return -1
    idx = 0
    res = [[0 for i in range(B)]for i in range(A)]
    for i in range(N):
        for j in range(M):
            res[idx // B][idx % B] = mat[i][j]
            idx += 1
    for i in range(A):
        for j in range(B):
            print(res[i][j], end=" ")
        print()


if __name__ == '__main__':
    mat = [[1, 2, 3, 4, 5, 6]]
    A = 2
    B = 3
    N = len(mat)
    M = len(mat[0])
    ConstMatrix(mat, N, M, A, B)

# Expected output:
1 2 3 
4 5 6
# modify given array by reducing each element by its next smaller element | function to print the final array after reducing each array element by its next smaller element ; initialize stack ; to store the corresponding element ; if stack is not empty ; if top element is smaller than the current element ; keep popping until stack is empty or top element is greater than the current element ; if stack is not empty ; push current element ; final array ; 
def printFinalPrices(arr):
    minStk = []
    reduce = [0] * len(arr)
    for i in range(len(arr) - 1, -1, -1):
        if minStk:
            if minStk[-1] <= arr[i]:
                reduce[i] = minStk[-1]
            else:
                while minStk and minStk[-1] > arr[i]:
                    minStk .pop()
                if minStk:
                    reduce[i] = minStk[-1]
        minStk .append(arr[i])
    for i in range(len(arr)):
        print(arr[i] - reduce[i], end=' ')


if __name__ == '__main__':
    arr = [8, 4, 6, 2, 3]
    printFinalPrices(arr)

# Expected output:
4 2 4 2 3
# generate array having differences between count of occurrences of every array element on its left and right | function to construct array of differences of counts on the left and right of the given array ; initialize left and right frequency arrays ; construct left cumulative frequency table ; construct right cumulative frequency table ; print the result ; 
def constructArray(A, N):
    left = [0] * (N + 1)
    right = [0] * (N + 1)
    X = [0] * (N + 1)
    Y = [0] * (N + 1)
    for i in range(0, N):
        X[i] = left[A[i]]
        left[A[i]] += 1
    for i in range(N - 1, -1, -1):
        Y[i] = right[A[i]]
        right[A[i]] += 1
    for i in range(0, N):
        print(Y[i] - X[i], end=" ")


if __name__ == '__main__':
    A = [3, 2, 1, 2, 3]
    N = len(A)
    constructArray(A, N)

# Expected output:
1 1 0 -1 -1
# generate an alternate odd | function to prthe required sequence ; print ith odd number ; 
def findNumbers(n):
    i = 0
    while (i <= n):
        print(2 * i * i + 4 * i + 1 + i % 2, end=" ")
        i += 1


n = 6
findNumbers(n)

# Expected output:
1 8 17 32 49 72 97
# program to calculate gross salary of a person | function to calculate the salary of the person ; condition to compute the allowance for the person ; calculate gross salary ; 
def computeSalary(basic, grade):
    hra = 0.2 * basic
    da = 0.5 * basic
    pf = 0.11 * basic
    if grade == 'A':
        allowance = 1700.0
    elif grade == 'B':
        allowance = 1500.0
    else:
        allowance = 1300.0
    gross = round(basic + hra + da + allowance - pf)
    return gross


if __name__ == '__main__':
    basic = 10000
    grade = 'A'
    print(computeSalary(basic, grade))

# Expected output:
17600
# rearrange and update array elements as specified by the given queries | python3 program to implement the above approach ; function to perform the given operations ; dequeue to store the array elements ; insert all element of the array into the dequeue ; stores the size of the queue ; traverse each query ; query for left shift . ; extract the element at the front of the queue ; pop the element at the front of the queue ; push the element at the back of the queue ; query for right shift ; extract the element at the back of the queue ; pop the element at the back of the queue ; push the element at the front of the queue ; query for update ; query to get the value ; 

from collections import deque


def Queries(arr, N, Q):
    dq = deque()
    for i in range(N):
        dq .append(arr[i])
    sz = len(Q)
    for i in range(sz):
        if (Q[i][0] == 0):
            front = dq[0]
            dq .popleft()
            dq .appendleft(front)
        elif (Q[i][0] == 1):
            back = dq[N - 1]
            dq .popleft()
            dq .appendleft(back)
        elif (Q[i][0] == 2):
            dq[Q[i][1]] = Q[i][2]
        else:
            print(dq[Q[i][1]], end=" ")


if __name__ == '__main__':
    arr = [1, 2, 3, 4, 5]
    N = len(arr)
    Q = [[0], [1], [3, 1], [2, 2, 54], [3, 2]]
    Queries(arr, N, Q)

# Expected output:
2 54
# size of smallest subarray to be removed to make count of array elements greater and smaller than k equal | python3 program to implement the above approach ; function ot find the length of the smallest subarray ; stores ( prefix sum , index ) as ( key , value ) mappings ; iterate till n ; update the prefixsum ; update the length ; put the latest index to find the minimum length ; update the length ; return the answer ; function to find the length of the largest subarray ; stores the sum of all array elements after modification ; change greater than k to 1 ; change smaller than k to - 1 ; change equal to k to 0 ; update total_sum ; no deletion required , return 0 ; delete smallest subarray that has sum = total_sum ; 

import sys


def smallSubarray(arr, n, total_sum):
    m = {}
    length = sys .maxsize
    prefixSum = 0
    for i in range(n):
        prefixSum += arr[i]
        if (prefixSum == total_sum):
            length = min(length, i + 1)
        m[prefixSum] = i
        if ((prefixSum - total_sum) in m .keys()):
            length = min(length, i - m[prefixSum - total_sum])
    return length


def smallestSubarrayremoved(arr, n, k):
    total_sum = 0
    for i in range(n):
        if (arr[i] > k):
            arr[i] = 1
        elif (arr[i] < k):
            arr[i] = -1
        else:
            arr[i] = 0
        total_sum += arr[i]
    if (total_sum == 0):
        return 0
    else:
        return smallSubarray(arr, n, total_sum)


arr = [12, 16, 12, 13, 10]
K = 13
n = len(arr)
print(smallestSubarrayremoved(arr, n, K))

# Expected output:
3
# balanced ternary number system | python3 program to convert positive decimals into balanced ternary system ; 
def balancedTernary(n):
    output = ""
    while (n > 0):
        rem = n % 3
        n = n // 3
        if (rem == 2):
            rem = -1
            n += 1
        if (rem == 0):
            output = '0' + output
        else:
            if (rem == 1):
                output = '1' + output
            else:
                output = 'Z' + output
    return output


n = 238
print("Equivalent Balanced Ternary of", n, "is:", balancedTernary(n))

# Expected output:
Equivalent Balanced Ternary of 238 is: 100Z11
# spt function or smallest parts function of a given number | python3 implementation to find the spt function to given number ; variable to store spt function of a number ; function to add value of frequency of minimum element among all representations of n ; find the value of frequency of minimum element ; calculate spt ; recursive function to find different ways in which n can be written as a sum of at one or more positive integers ; if sum becomes n , consider this representation ; start from previous element in the representation till n ; include current element from representation ; call function again with reduced sum ; backtrack - remove current element from representation ; function to find the spt function ; using recurrence find different ways in which n can be written as a sum of at 1 or more positive integers ; 

import sys
spt = 0


def printVector(arr):
    global spt
    min_i = sys .maxsize
    for i in range(len(arr)):
        min_i = min(min_i, arr[i])
    freq = arr .count(min_i)
    spt += freq


def findWays(arr, i, n):
    if (n == 0):
        printVector(arr)
    for j in range(i, n + 1):
        arr .append(j)
        findWays(arr, j, n - j)
        del arr[-1]


def spt_function(n):
    arr = []
    findWays(arr, 1, n)
    print(spt)


if __name__ == '__main__':
    N = 4
    spt_function(N)

# Expected output:
10
# find initial integral solution of linear diophantine equation if finite solution exists | python3 program for the above approach ; function to implement the extended euclid algorithm ; base case ; recursively find the gcd ; function to prlet the solutions of the given equations ax + by = c ; condition for infinite solutions ; condition for no solutions exist ; condition for no solutions exist ; print the solution ; 

import math
x, y = 0, 0


def gcd_extend(a, b):
    global x, y
    if (b == 0):
        x = 1
        y = 0
        return a
    else:
        g = gcd_extend(b, a % b)
        x1, y1 = x, y
        x = y1
        y = x1 - math .floor(a / b) * y1
        return g


def print_solution(a, b, c):
    if (a == 0 and b == 0):
        if (c == 0):
            print("Infinite Solutions Exist")
        else:
            print("No Solution exists")
    gcd = gcd_extend(a, b)
    if (c % gcd != 0):
        print("No Solution exists")
    else:
        print("x = ", int(x * (c / gcd)), ", y = ", int(y * (c / gcd)), sep="")


a = 4
b = 18
c = 10
print_solution(a, b, c)

# Expected output:
x = -20, y = 5
# count of pairs whose bitwise and is a power of 2 | function to check if x is power of 2 ; returns true if x is a power of 2 ; function to return the number of valid pairs ; iterate for all possible pairs ; bitwise and value of the pair is passed ; return the final count ;  ; 
def check(x):
    return x and (not (x & (x - 1)))


def count(arr, n):
    cnt = 0
    for i in range(n - 1):
        for j in range(i + 1, n):
            if check(arr[i] & arr[j]):
                cnt = cnt + 1
    return cnt


arr = [6, 4, 2, 3]
n = len(arr)
print(count(arr, n))

# Expected output:
4
# count of all possible pairs of array elements with same parity | function to return the answer ; generate all possible pairs ; increment the count if both even or both odd ; 
def countPairs(A, n):
    count = 0
    for i in range(n):
        for j in range(i + 1, n):
            if ((A[i] %
                 2 == 0 and A[j] %
                 2 == 0) or (A[i] %
                2 != 0 and A[j] %
                             2 != 0)):
                count += 1
    return count


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

# Expected output:
6
# smallest number whose sum of digits is square of n | function to return smallest number whose sum of digits is n ^ 2 ; 
def smallestNum(n):
    return ((n * n % 9 + 1) * pow(10, int(n * n / 9)) - 1)


N = 4
print(smallestNum(N))

# Expected output:
79
# second heptagonal numbers | function to find n - th term in the series ; 
def findNthTerm(n):
    print(n * (5 * n + 3) // 2)


N = 4
findNthTerm(N)

# Expected output:
46
# weakly prime numbers | function to check if n is prime ; corner cases ; this is checked so that we can skip middle five numbers in below loop ; function to check if n is a weakly prime number ; number should be prime ; converting n to string ; loop to change digit at every character one by one . ; loop to store every digit one by one at index j ; 
def isPrime(n):
    if (n <= 1):
        return False
    if (n <= 3):
        return True
    if (n % 2 == 0 or n % 3 == 0):
        return False
    for i in range(5, int(n ** 0.5) + 1, 6):
        if (n % i == 0 or n % (i + 2) == 0):
            return False
    return True


def isWeaklyPrimeNum(N):
    if (isPrime(N) == False):
        return False
    s = str(N)
    for j in range(len(s)):
        str1 = s
        for i in range(10):
            c = str(i)
            str1 = str1[:j] + c + str1[j + 1:]
            Num = int(str1)
            if (str1[j] != s[j] and isPrime(Num)):
                return False
    return True


n = 294001
if (isWeaklyPrimeNum(n)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# unprimeable numbers | function to check if n is prime ; corner cases ; this is checked so that we can skip middle five numbers in below loop ; function to check if n is a unprimeable number ; number should be composite ; converting n to string ; loop to change digit at every character one by one . ; loop to store every digit one by one at index j ; 
def isPrime(n):
    if (n <= 1):
        return False
    if (n <= 3):
        return True
    if (n % 2 == 0 or n % 3 == 0):
        return False
    for i in range(5, int(n ** 0.5) + 1, 6):
        if (n % i == 0 or n % (i + 2) == 0):
            return False
    return True


def isUnPrimeableNum(N):
    if (isPrime(N)):
        return False
    s = str(N)
    for j in range(len(s)):
        str1 = s
        for i in range(10):
            c = str(i)
            str1 = str1[:j] + c + str1[j + 1:]
            Num = int(str1)
            if (str1[j] != s[j] and isPrime(Num)):
                return False
    return True


n = 200
if (isUnPrimeableNum(n)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# find the nth row in pascal 's triangle | function to find the elements of rowindex in pascal 's triangle ; 1 st element of every row is 1 ; check if the row that has to be returned is the first row ; generate the previous row ; generate the elements of the current row by the help of the previous row ; return the row ; 
def getRow(rowIndex):
    currow = []
    currow .append(1)
    if (rowIndex == 0):
        return currow
    prev = getRow(rowIndex - 1)
    for i in range(1, len(prev)):
        curr = prev[i - 1] + prev[i]
        currow .append(curr)
    currow .append(1)
    return currow


n = 3
arr = getRow(n)
for i in range(len(arr)):
    if (i == (len(arr) - 1)):
        print(arr[i])
    else:
        print(arr[i], end=", ")

# Expected output:
1, 3, 3, 1
# all possible values of floor ( n / k ) for all values of k | function to print all possible values of floor ( n / k ) ; iterate from 1 to n + 1 ; 
def allQuotients(N):
    s = set()
    for k in range(1, N + 2):
        s .add(N // k)
    for it in s:
        print(it, end=' ')


if __name__ == '__main__':
    N = 5
    allQuotients(N)

# Expected output:
0 1 2 5
# greatest odd factor of an even number | python3 program for the above approach ; function to print greatest odd factor ; initialize i with 1 ; iterate till i <= pow_2 ; find the pow ( 2 , i ) ; if factor is odd , then print the number and break ; 

import math


def greatestOddFactor(n):
    pow_2 = int(math .log(n, 2))
    i = 1
    while i <= pow_2:
        fac_2 = (2 ** i)
        if (n % fac_2 == 0):
            if ((n // fac_2) % 2 == 1):
                print(n // fac_2)
                break
        i += 1


N = 8642
greatestOddFactor(N)

# Expected output:
4321
# find the element in a linked list with frequency at least n / 3 | structure of a node for the linked list ; function to find and return the element with frequency of at least n / 3 ; candidates for being the required majority element ; store the frequencies of the respective candidates ; iterate all nodes ; increase frequency of candidate s ; increase frequency of candidate t ; set the new sting as candidate for majority ; set the new sting as second candidate for majority ; decrease the frequency ; check the frequency of two final selected candidate linklist ; increase the frequency of first candidate ; increase the frequency of second candidate ; return the string with higher frequency ; 

class Node:
    def __init__(self, s):
        self .i = s
        self .next = None


def Majority_in_linklist(head):
    s, t = "", ""
    p, q = 0, 0
    ptr = None
    while head is not None:
        if s == head .i:
            p = p + 1
        else:
            if t == head .i:
                q = q + 1
            else:
                if p == 0:
                    s = head .i
                    p = 1
                else:
                    if q == 0:
                        t = head .i
                        q = 1
                    else:
                        p = p - 1
                        q = q - 1
        head = head .next
    head = ptr
    p = 0
    q = 0
    while head is not None:
        if s == head .i:
            p = 1
        else:
            if t == head .i:
                q = 1
        head = head .next
    if p > q:
        return s
    else:
        return t


ptr = None
head = Node("geeks")
head .next = Node("geeks")
head .next .next = Node("abcd")
head .next .next .next = Node("game")
head .next .next .next .next = Node("game")
head .next .next .next .next .next = Node("knight")
head .next .next .next .next .next .next = Node("harry")
head .next .next .next .next .next .next .next = Node("geeks")
print(Majority_in_linklist(head))

# Expected output:
geeks
# form smallest number using indices of numbers chosen from array with sum less than s | function to find the minimum number which have maximum length ; find maximum length of number ; find minimum number which have maximum length ; 
def max_number(arr, sum):
    frac = [0] * 9
    maxi = -10 ** 9
    pos = 0
    for i in range(9):
        frac[i] = sum // arr[i]
        if (frac[i] > maxi):
            pos = i
            maxi = frac[i]
    an = str((pos + 1)) * maxi
    sum -= maxi * arr[pos]
    ans = [i for i in an]
    for i in range(maxi):
        for j in range(1, 10):
            if (sum + arr[pos] - arr[j - 1] >= 0):
                ans[i] = str(j)
                sum += arr[pos] - arr[j - 1]
                break
    if (maxi == 0):
        return 0
    else:
        return "".join(ans)


if __name__ == '__main__':
    arr = [3, 4, 2, 4, 6, 5, 4, 2, 3]
    s = 13
    print(max_number(arr, s))

# Expected output:
133333
# check if given intervals can be made non | function to check if two intervals overlap with each other ; condition to check if the intervals overlap ; function to check if there is a existing overlapping intervals ; path compression ; union of two intervals returns true if there is a overlapping with the same another interval ; both have same another overlapping interval ; function to check if the intervals can be added by x to form non - overlapping intervals ; if the intervals overlaps we will union them ; there is no cycle ; 
def checkOverlapping(a, b):
    a, b = max(a, b), min(a, b)
    if b[0] <= a[0] <= b[1]:
        return True
    return False


def find(a, i):
    if a[i] == i:
        return i
    a[i] = find(a, a[i])
    return a[i]


def union(a, x, y):
    xs = find(a, x)
    ys = find(a, y)
    if xs == ys:
        return True
    a[ys] = xs
    return False


def checkNonOverlapping(arr, n):
    dsu = [i for i in range(n + 1)]
    for i in range(n):
        for j in range(i + 1, n):
            if checkOverlapping(arr[i], arr[j]):
                if union(dsu, i, j):
                    return False
    return True


if __name__ == "__main__":
    arr = [[1, 4], [2, 2], [2, 3]]
    n = len(arr)
    print("YES"if checkNonOverlapping(arr, n)else "NO")

# Expected output:
NO
# number formed after k times repeated addition of smallest divisor of n | python3 program to find the kth number formed after repeated addition of smallest divisor of n ; if n is even ; if n is odd ; add smallest divisor to n ; updated n is even ; 

import math


def FindValue(N, K):
    if (N % 2 == 0):
        N = N + 2 * K
    else:
        for i in range(2, (int)(math .sqrt(N)) + 1):
            if (N % i == 0):
                break
        N = N + i
        N = N + 2 * (K - 1)
    print(N)


if __name__ == "__main__":
    N = 9
    K = 4
    FindValue(N, K)

# Expected output:
18
# find last digit in factorial | python3 program to find last digit in factorial n . ; explicitly handle all numbers less than or equal to 4 ; for all numbers greater than 4 the last digit is 0 ; 
def lastDigitFactorial(n):
    if (n == 0):
        return 1
    elif (n <= 2):
        return n
    elif (n == 3):
        return 6
    elif (n == 4):
        return 4
    else:
        return 0


print(lastDigitFactorial(6))

# Expected output:
0
# program to convert hexa | function to convert haxadecimal to bcd ; iterating through the digits ; conversion into equivalent bcd ; 
def HexaDecimaltoBCD(str):
    for i in range(len(str)):
        print("{0:04b}".format(int(str[i], 16)), end=" ")


str = "11F"
HexaDecimaltoBCD(str)

# Expected output:
0001 0001 1111
# find the sum of the first nth heptadecagonal number | function to find the n - th heptadecagonal number ; formula to calculate nth heptadecagonal number ; function to find the sum of the first n heptadecagonal numbers ; variable to store the sum ; iterate from 1 to n ; finding the sum ; 
def heptadecagonal_num(n):
    return ((15 * n * n) - 13 * n) // 2


def sum_heptadecagonal_num(n):
    summ = 0
    for i in range(1, n + 1):
        summ += heptadecagonal_num(i)
    return summ


if __name__ == '__main__':
    n = 5
    print(sum_heptadecagonal_num(n))

# Expected output:
315
# program to check if n is a centered pentagonal number or not | python3 program for the above approach ; function to check if number n is a centered pentagonal number ; condition to check if n is a centered pentagonal number ; 

import numpy as np


def isCenteredpentagonal(N):
    n = (5 + np .sqrt(40 * N - 15)) / 10
    return (n - int(n)) == 0


N = 6
if (isCenteredpentagonal(N)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# program to check if n is a dodecagonal number | python3 program for the above approach ; function to check if number n is a dodecagonal number or not ; condition to check if the n is a dodecagonal number ; 

import numpy as np


def isdodecagonal(N):
    n = (4 + np .sqrt(20 * N + 16)) / 10
    return (n - int(n)) == 0


N = 12
if (isdodecagonal(N)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes