giulio98/xlcost-single-prompt huggingface dataset:
# stella octangula number | returns value of n * ( 2 * n * n - 1 ) ; finds if a value of f ( n ) is equal to x where n is in interval [ low . . high ] ; returns true if x isstella octangula number . else returns false . ; find ' high ' for binary search by repeated doubling ; if condition is satisfied for a power of 2. ; call binary search ; 
def f(n):
    return n * (2 * n * n - 1)


def binarySearch(low, high, x):
    while (low <= high):
        mid = int((low + high) // 2)
        if (f(mid) < x):
            low = mid + 1
        elif (f(mid) > x):
            high = mid - 1
        else:
            return True
    return False


def isStellaOctangula(x):
    if (x == 0):
        return True
    i = 1
    while (f(i) < x):
        i = i * 2
    if (f(i) == x):
        return True
    return binarySearch(i / 2, i, x)


n = 51
if (isStellaOctangula(n)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# sort the given string using character search | python 3 implementation to sort the given string without using any sorting technique ; a character array to store the no . of occurrences of each character between ' a ' to 'z ; to store the final sorted string ; to store each occurrence of character by relative indexing ; to traverse the character array and append it to new_str ; 
def sortString(st, n):

    arr = [0] * 26
    new_str = ""
    for i in range(n):
        arr[ord(st[i]) - ord('a')] += 1
    for i in range(26):
        while (arr[i] > 0):
            new_str += chr(i + ord('a'))
            arr[i] -= 1
    return new_str


if __name__ == "__main__":
    st = "geeksforgeeks"
    n = len(st)
    print(sortString(st, n))

# Expected output:
eeeefggkkorss
# maximum sum of elements from each row in the matrix | python program to find row - wise maximum element sum considering elements in increasing order . ; function to perform given task ; getting the maximum element from last row ; comparing it with the elements of above rows ; maximum of current row . ; if we could not an element smaller than prev_max . ; 

N = 3


def getGreatestSum(a):
    prev_max = 0
    for j in range(N):
        if (prev_max < a[N - 1][j]):
            prev_max = a[N - 1][j]
    sum = prev_max
    for i in range(N - 2, -1, -1):
        curr_max = -2147483648
        for j in range(N):
            if (prev_max > a[i][j] and a[i][j] > curr_max):
                curr_max = a[i][j]
        if (curr_max == -2147483648):
            return -1
        prev_max = curr_max
        sum = sum + prev_max
    return sum


a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(getGreatestSum(a))
b = [[4, 5, 6], [4, 5, 6], [4, 5, 6]]
print(getGreatestSum(b))

# Expected output:
18
15
# find the number of times every day occurs in a month | python program to count occurrence of days in a month ; function to find occurrences ; stores days in a week ; initialize all counts as 4. ; find index of the first day ; number of days whose occurrence will be 5 ; mark the occurrence to be 5 of n - 28 days ; print the days ; 

import math


def occurrenceDays(n, firstday):
    days = [
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday",
        "Sunday"]
    count = [4 for i in range(0, 7)]
    pos = -1
    for i in range(0, 7):
        if (firstday == days[i]):
            pos = i
            break
    inc = n - 28
    for i in range(pos, pos + inc):
        if (i > 6):
            count[i % 7] = 5
        else:
            count[i] = 5
    for i in range(0, 7):
        print(days[i], " ", count[i])


n = 31
firstday = "Tuesday"
occurrenceDays(n, firstday)

# Expected output:
Monday   4
Tuesday   5
Wednesday   5
Thursday   5
Friday   4
Saturday   4
Sunday   4
# value of k | python3 code to find k - th element after append and insert middle operations ; ans = n middle element of the sequence ; length of the resulting sequence . ; updating the middle element of next sequence ; moving to the left side of the middle element . ; moving to the right side of the middle element . ; 

import math


def findElement(n, k):
    ans = n
    left = 1
    right = math.pow(2, n) - 1
    while 1:
        mid = int((left + right) / 2)
        if k == mid:
            print(ans)
            break
        ans -= 1
        if k < mid:
            right = mid - 1
        else:
            left = mid + 1


n = 4
k = 8
findElement(n, k)

# Expected output:
4
# print pair with maximum and value in an array | utility function to check number of elements having set msb as of pattern ; function for finding maximum and value pair ; iterate over total of 30 bits from msb to lsb ; find the count of element having set msb ; if count >= 2 set particular bit in result ; find the elements ; print the pair of elements ; inc count value after printing element ; return the result value ; 
def checkBit(pattern, arr, n):
    count = 0
    for i in range(0, n):
        if ((pattern & arr[i]) == pattern):
            count += 1
    return count


def maxAND(arr, n):
    res = 0
    for bit in range(31, -1, -1):
        count = checkBit(res | (1 << bit), arr, n)
        if (count >= 2):
            res |= (1 << bit)
    if (res == 0):
        print("Not Possible")
    else:
        print("Pair = ", end="")
        count = 0
        i = 0
        while (i < n and count < 2):
            if ((arr[i] & res) == res):
                count += 1
                print(arr[i], end=" ")
            i += 1
    return res


arr = [4, 8, 6, 2]
n = len(arr)
print("MaximumANDValue=", maxAND(arr, n))

# Expected output:
Pair = 4 6 MaximumANDValue= 4
# probability of choosing a random pair with maximum sum in an array | function to get max first and second ; if current element is smaller than first , then update both first and second ; if arr [ i ] is in between first and second then update second ; cnt1 += 1 frequency of first maximum ; cnt2 += 1 frequency of second maximum ; returns probability of choosing a pair with maximum sum . ; 
def countMaxSumPairs(a, n):

    first = 0
    second = 0
    for i in range(n):
        if (a[i] > first):
            second = first
            first = a[i]
        elif (a[i] > second and a[i] != first):
            second = a[i]

    cnt1 = 0
    cnt2 = 0
    for i in range(n):
        if (a[i] == first):
            cnt1 += 1
        if (a[i] == second):
            cnt2 += 1

    if (cnt1 == 1):
        return cnt2

    if (cnt1 > 1):
        return cnt1 * (cnt1 - 1) / 2


def findMaxSumProbability(a, n):

    total = n * (n - 1) / 2
    max_sum_pairs = countMaxSumPairs(a, n)
    return max_sum_pairs / total


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

# Expected output:
0.3333333333333333
# find if given number is sum of first n natural numbers | function to find no . of elements to be added from 1 to get n ; start adding numbers from 1 ; if sum becomes equal to s return n ; 
def findS(s):
    _sum = 0
    n = 1
    while (_sum < s):
        _sum += n
        n += 1
    n -= 1
    if _sum == s:
        return n
    return -1


s = 15
n = findS(s)
if n == -1:
    print("-1")
else:
    print(n)

# Expected output:
5
# find if given number is sum of first n natural numbers | python3 program of the above approach ; function to check if the s is the sum of first n natural number ; solution of quadratic equation ; condition to check if the solution is a integer ; 

import math


def isvalid(s):
    k = (-1 + math .sqrt(1 + 8 * s)) / 2
    if (math .ceil(k) == math .floor(k)):
        return int(k)
    else:
        return -1


s = 15
print(isvalid(s))

# Expected output:
5
# save from bishop in chessboard | python program to find total safe position to place your bishop ; function to calc total safe position ; i , j denotes row and column of position of bishop ; calc distance in four direction ; calc total sum of distance + 1 for unsafe positions ; return total safe positions ; 

import math


def calcSafe(pos):
    j = pos % 10
    i = pos / 10
    dis_11 = min(abs(1 - i), abs(1 - j))
    dis_18 = min(abs(1 - i), abs(8 - j))
    dis_81 = min(abs(8 - i), abs(1 - j))
    dis_88 = min(abs(8 - i), abs(8 - j))
    sum = (dis_11 + dis_18 + dis_81 + dis_88 + 1)
    return (64 - sum)


pos = 34
print("Safe Positions = ", math .ceil(calcSafe(pos)))

# Expected output:
Safe Positions =  52
# count number of elements between two given elements in array | function to count number of elements occurs between the elements . ; find num1 ; if num1 is not present or present at end ; find num2 ; if num2 is not present ; return number of elements between the two elements . ; 
def getCount(arr, n, num1, num2):
    for i in range(0, n):
        if (arr[i] == num1):
            break
    if (i >= n - 1):
        return 0
    for j in range(n - 1, i + 1, -1):
        if (arr[j] == num2):
            break
    if (j == i):
        return 0
    return (j - i - 1)


arr = [3, 5, 7, 6, 4, 9, 12, 4, 8]
n = len(arr)
num1 = 5
num2 = 4
print(getCount(arr, n, num1, num2))

# Expected output:
5
# best meeting point in 2d binary array | python program to find best meeting point in 2d array ; find all members home 's position ; sort positions so we can find most beneficial point ; middle position will always beneficial for all group members but it will be sorted which we have already done ; now find total distance from best meeting point ( x , y ) using manhattan distance formula ; 

ROW = 3
COL = 5


def minTotalDistance(grid: list) -> int:
    if ROW == 0 or COL == 0:
        return 0
    vertical = []
    horizontal = []
    for i in range(ROW):
        for j in range(COL):
            if grid[i][j] == 1:
                vertical .append(i)
                horizontal .append(j)
    vertical .sort()
    horizontal .sort()
    size = len(vertical) // 2
    x = vertical[size]
    y = horizontal[size]
    distance = 0
    for i in range(ROW):
        for j in range(COL):
            if grid[i][j] == 1:
                distance += abs(x - i) + abs(y - j)
    return distance


if __name__ == "__main__":
    grid = [[1, 0, 1, 0, 1], [0, 1, 0, 0, 0], [0, 1, 1, 0, 0]]
    print(minTotalDistance(grid))

# Expected output:
11
# count numbers with difference between number and its digit sum greater than specific value | utility method to get sum of digits of k ; loop until k is not zero ; method returns count of numbers smaller than n , satisfying difference condition ; binary search while loop ; if difference between number and its sum of digit is smaller than given difference then smallest number will be on left side ; if difference between number and its sum of digit greater than equal to given difference then smallest number will be on right side ; return the difference between ' smallest ▁ number ▁ ▁ found ' and ' n ' as result ; 
def sumOfDigit(K):
    sod = 0
    while (K):
        sod = sod + K % 10
        K = K // 10
    return sod


def totalNumbersWithSpecificDifference(N, diff):
    low = 1
    high = N
    while (low <= high):
        mid = (low + high) // 2
        if (mid - sumOfDigit(mid) < diff):
            low = mid + 1
        else:
            high = mid - 1
    return (N - high)


N = 13
diff = 2
print(totalNumbersWithSpecificDifference(N, diff))

# Expected output:
4
# randomized binary search algorithm | to generate random number between x and y ie . . [ x , y ] ; a iterative randomized binary search function . it returns location of x in given array arr [ l . . r ] if present , otherwise - 1 ; here we have defined middle as random index between l and r ie . . [ l , r ] ; check if x is present at mid ; if x greater , ignore left half ; if x is smaller , ignore right half ; if we reach here , then element was not present ; 

from random import randint


def getRandom(x, y):
    return randint(x, y)


def randomizedBinarySearch(arr, l, r, x):
    while (l <= r):
        m = getRandom(l, r)
        if (arr[m] == x):
            return m
        if (arr[m] < x):
            l = m + 1
        else:
            r = m - 1
    return -1


arr = [2, 3, 4, 10, 40]
n = len(arr)
x = 10
result = randomizedBinarySearch(arr, 0, n - 1, x)
if result == 1:
    print("Element is not present in array")
else:
    print("Element is present at index", result)

# Expected output:
Element is present at index 3
# number of buildings facing the sun | returns count buildings that can see sunlight ; initialuze result ( note that first building always sees sunlight ) ; start traversing element ; if curr_element is maximum or current element is equal , update maximum and increment count ; 
def countBuildings(arr, n):
    count = 1
    curr_max = arr[0]
    for i in range(1, n):
        if (arr[i] > curr_max or arr[i] == curr_max):
            count += 1
            curr_max = arr[i]
    return count


arr = [7, 4, 8, 2, 9]
n = len(arr)
print(countBuildings(arr, n))

# Expected output:
3
# find index of an extra element present in one sorted array | returns index of extra . element in arr1 [ ] n is size of arr2 [ ] . size of arr1 [ ] is n - 1. ; 
def findExtra(arr1, arr2, n):
    for i in range(0, n):
        if (arr1[i] != arr2[i]):
            return i
    return n


arr1 = [2, 4, 6, 8, 10, 12, 13]
arr2 = [2, 4, 6, 8, 10, 12]
n = len(arr2)
print(findExtra(arr1, arr2, n))

# Expected output:
6
# find index of an extra element present in one sorted array | returns index of extra element in arr1 [ ] . n is size of arr2 [ ] . size of arr1 [ ] is n - 1. ; left and right are end points denoting the current range . ; if middle element is same of both arrays , it means that extra element is after mid so we update left to mid + 1 ; if middle element is different of the arrays , it means that the index we are searching for is either mid , or before mid . hence we update right to mid - 1. ; when right is greater than left our search is complete . ; 
def findExtra(arr1, arr2, n):

    index = n
    left = 0
    right = n - 1
    while (left <= right):
        mid = (int)((left + right) / 2)
        if (arr2[mid] == arr1[mid]):
            left = mid + 1
        else:
            index = mid
            right = mid - 1
    return index


arr1 = [2, 4, 6, 8, 10, 12, 13]
arr2 = [2, 4, 6, 8, 10, 12]
n = len(arr2)
print(findExtra(arr1, arr2, n))

# Expected output:
6
# make all array elements equal with minimum cost | utility method to compute cost , when all values of array are made equal to x ; method to find minimum cost to make all elements equal ; setting limits for ternary search by smallest and largest element ; loop until difference between low and high become less than 3 , because after that mid1 and mid2 will start repeating ; mid1 and mid2 are representative array equal values of search space ; if mid2 point gives more total cost , skip third part ; if mid1 point gives more total cost , skip first part ; computecost gets optimum cost by sending average of low and high as x ; 
def computeCost(arr, N, X):
    cost = 0
    for i in range(N):
        cost += abs(arr[i] - X)
    return cost


def minCostToMakeElementEqual(arr, N):
    low = high = arr[0]
    for i in range(N):
        if (low > arr[i]):
            low = arr[i]
        if (high < arr[i]):
            high = arr[i]
    while ((high - low) > 2):
        mid1 = low + (high - low) // 3
        mid2 = high - (high - low) // 3
        cost1 = computeCost(arr, N, mid1)
        cost2 = computeCost(arr, N, mid2)
        if (cost1 < cost2):
            high = mid2
        else:
            low = mid1
    return computeCost(arr, N, (low + high) // 2)


arr = [1, 100, 101]
N = len(arr)
print(minCostToMakeElementEqual(arr, N))

# Expected output:
100
# minimum number of jumps required to sort numbers placed on a number line | function to find the minimum number of jumps required to sort the array ; base case ; store the required result ; stores the current position of elements and their respective maximum jump ; used to check if a position is already taken by another element ; stores the sorted array a [ ] ; traverse the array w [ ] & update positions jumps array a [ ] ; sort the array a [ ] ; traverse the array a [ ] over the range [ 1 , n - 1 ] ; store the index of current element and its just smaller element in array w [ ] ; iterate until current element position is at most its just smaller element position ; update the position of the current element ; print the result ; 
def minJumps(w, l, n):
    if (n == 1):
        print(0)
        return
    ans = 0
    pos = {}
    jump = {}
    filled = {}
    a = [0 for i in range(n)]
    for i in range(n):
        pos[w[i]] = i
        filled[i] = True
        jump[w[i]] = l[i]
        a[i] = w[i]
    a .sort()
    for curr in range(1, n, 1):
        currElementPos = pos[a[curr]]
        prevElementPos = pos[a[curr - 1]]
        if (currElementPos > prevElementPos):
            continue
        while (currElementPos <= prevElementPos or (
                currElementPos in filled and filled[currElementPos])):
            currElementPos += jump[a[curr]]
            ans += 1
        pos[a[curr]] = currElementPos
        filled[currElementPos] = True
    print(ans)


if __name__ == '__main__':
    W = [2, 1, 4, 3]
    L = [4, 1, 2, 4]
    N = len(W)
    minJumps(W, L, N)

# Expected output:
5
# make an array strictly increasing by repeatedly subtracting and adding arr [ i | function to check if an array can be made strictly increasing ; traverse the given array arr [ ] ; update the value of p , arr [ i ] , and arr [ i - 1 ] ; traverse the given array ; check if the array arr [ ] is strictly increasing or not ; otherwise , array is increasing order , pryes ; 
def check(arr, n):
    for i in range(1, n):
        if (arr[i - 1] >= (i - 1)):
            p = arr[i - 1] - (i - 1)
            arr[i] += p
            arr[i - 1] -= p
    for i in range(1, n):
        if (arr[i] <= arr[i - 1]):
            print("No")
            return
    print("Yes")


if __name__ == '__main__':
    arr = [1, 5, 2, 7, 6]
    N = len(arr)
    check(arr, N)

# Expected output:
Yes
# rearrange array to make decimal equivalents of reversed binary representations of array elements sorted | function to reverse the bits of a number ; stores the reversed number ; divide rev by 2 ; if the value of n is odd ; update the value of n ; return the final value of rev ; function for rearranging the array element according to the given rules ; stores the new array elements ; function for rearranging the array ; stores the new array ; function to sort the array by reversing the binary representation ; creating a new array ; sort the array with the key ; get arr from newarr ; print the sorted array ; 
def keyFunc(n):
    rev = 0
    while (n > 0):
        rev = rev << 1
        if (n & 1 == 1):
            rev = rev ^ 1
        n = n >> 1
    return rev


def getNew(arr):
    ans = []
    for i in arr:
        ans .append([keyFunc(i), i])
    return ans


def getArr(arr):
    ans = []
    for i in arr:
        ans .append(i[1])
    return ans


def sortArray(arr):
    newArr = sorted(getNew(arr))
    arr = getArr(newArr)
    print(arr)


arr = [43, 52, 61, 41]
sortArray(arr)

# Expected output:
[52, 41, 61, 43]
# minimize maximum array element by splitting array elements into powers of two at most k times | function to find the minimum value of the maximum element of the array by splitting at most k array element into perfect powers of 2 ; sort the array element in the ascending order ; reverse the array ; if count of 0 is equal to n ; otherwise , if k is greater than or equal to n ; otherwise ; 
def minimumSize(arr, N, K):
    arr .sort()
    arr .reverse()
    zero = arr .count(0)
    if zero == N:
        print(0)
    elif K >= N:
        print(1)
    else:
        print(arr[K])


arr = [2, 4, 8, 2]
K = 2
N = len(arr)
minimumSize(arr, N, K)

# Expected output:
2
# check if removal of a subsequence of non | function to check if it is possible to sort the array or not ; stores the index if there are two consecutive 1 's in the array ; traverse the given array ; check adjacent same elements having values 1 s ; if there are no two consecutive 1 s , then always remove all the 1 s from array & make it sorted ; if two consecutive 0 ' s ▁ are ▁ ▁ present ▁ after ▁ two ▁ consecutive ▁ ▁ 1' s then array can 't be sorted ; otherwise , print yes ; 
def isPossibleToSort(arr, N):
    idx = -1
    for i in range(1, N):
        if (arr[i] == 1 and arr[i - 1] == 1):
            idx = i
            break
    if (idx == -1):
        print("YES")
        return
    for i in range(idx + 1, N, 1):
        if (arr[i] == 0 and arr[i - 1] == 0):
            print("NO")
            return
    print("YES")


if __name__ == '__main__':
    arr = [1, 0, 1, 0, 1, 1, 0]
    N = len(arr)
    isPossibleToSort(arr, N)

# Expected output:
YES
# maximize ropes of consecutive length possible by connecting given ropes | function to find maximized count of ropes of consecutive length ; stores the maximum count of ropes of consecutive length ; sort the ropes by their length ; traverse the array ; if size of the current rope is less than or equal to current maximum possible size + 1 , update the range to cursize + ropes [ i ] ; if a rope of size ( cursize + 1 ) cannot be obtained ; 
def maxConsecutiveRopes(ropes, N):
    curSize = 0
    ropes = sorted(ropes)
    for i in range(N):
        if (ropes[i] <= curSize + 1):
            curSize = curSize + ropes[i]
        else:
            break
    return curSize


if __name__ == '__main__':
    N = 5
    ropes = [1, 2, 7, 1, 1]
    print(maxConsecutiveRopes(ropes, N))

# Expected output:
5
# maximum ranges that can be uniquely represented by any integer from the range | function to find the maximum number of ranges where each range can be uniquely represented by an integer ; sort the ranges in ascending order ; stores the count of ranges ; stores previously assigned range ; traverse the vector arr [ ] ; skip the similar ranges of size 1 ; find the range of integer available to be assigned ; check if an integer is available to be assigned ; update the previously assigned range ; update the count of range ; return the maximum count of ranges ; 
def maxRanges(arr, N):
    arr .sort()
    count = 1
    prev = arr[0]
    for i in range(1, N):
        last = arr[i - 1]
        current = arr[i]
        if (last[0] == current[0] and last[1] ==
                current[1] and current[1] == current[0]):
            continue
        start = max(prev[0], current[0] - 1)
        end = max(prev[1], current[1])
        if (end - start > 0):
            prev[0] = 1 + start
            prev[1] = end
            count += 1
    return count


if __name__ == "__main__":
    arr = [[1, 4], [4, 4], [2, 2], [3, 4], [1, 1]]
    N = len(arr)
    print(maxRanges(arr, N))

# Expected output:
4