giulio98/xlcost-single-prompt huggingface dataset:
# check if a number is divisible by 17 using bitwise operators | function to check recursively if the number is divisible by 17 or not ; if n = 0 or n = 17 then yes ; if n is less then 17 , not divisible by 17 ; reducing the number by floor ( n / 16 ) - n % 16 ; 
def isDivisibleby17(n):
    if (n == 0 or n == 17):
        return True
    if (n < 17):
        return False
    return isDivisibleby17((int)(n >> 4) - (int)(n & 15))


n = 35
if (isDivisibleby17(n)):
    print(n, "is divisible by 17")
else:
    print(n, "is not divisible by 17")

# Expected output:
35 is not divisible by 17
# largest number with binary representation is m 1 's and m | python3 program to find largest number smaller than equal to n with m set bits then m - 1 0 bits . ; returns largest number with m set bits then m - 1 0 bits . ; start with 2 bits . ; initial answer is 1 which meets the given condition ; check for all numbers ; compute the number ; if less then n ; increment m to get the next number ; 

import math


def answer(n):
    m = 2
    ans = 1
    r = 1
    while r < n:
        r = (int)((pow(2, m) - 1) * (pow(2, m - 1)))
        if r < n:
            ans = r
        m = m + 1
    return ans


print(answer(7))

# Expected output:
6
# find most significant set bit of a number | simple python3 program to find msb number for given n . ; 
def setBitNumber(n):
    if (n == 0):
        return 0
    msb = 0
    n = int(n / 2)
    while (n > 0):
        n = int(n / 2)
        msb += 1
    return (1 << msb)


n = 0
print(setBitNumber(n))

# Expected output:
0
# find most significant set bit of a number | python program to find msb number for given n . ; suppose n is 273 ( binary is 100010001 ) . it does following 100010001 | 010001000 = 110011001 ; this makes sure 4 bits ( from msb and including msb ) are set . it does following 110011001 | 001100110 = 111111111 ; increment n by 1 so that there is only one set bit which is just before original msb . n now becomes 1000000000 ; return original msb after shifting . n now becomes 100000000 ; 
def setBitNumber(n):
    n |= n >> 1
    n |= n >> 2
    n |= n >> 4
    n |= n >> 8
    n |= n >> 16
    n = n + 1
    return (n >> 1)


n = 273
print(setBitNumber(n))

# Expected output:
256
# count trailing zero bits using lookup table | python 3 code for counting trailing zeros in binary representation of a number ; 
def countTrailingZero(x):
    count = 0
    while ((x & 1) == 0):
        x = x >> 1
        count += 1
    return count


if __name__ == '__main__':
    print(countTrailingZero(11))

# Expected output:
0
# count trailing zero bits using lookup table | python3 code for counting trailing zeros in binary representation of a number ; map a bit value mod 37 to its position ; only difference between ( x and - x ) is the value of signed magnitude ( leftmostbit ) negative numbers signed bit is 1 ; 
def countTrailingZero(x):
    lookup = [
        32,
        0,
        1,
        26,
        2,
        23,
        27,
        0,
        3,
        16,
        24,
        30,
        28,
        11,
        0,
        13,
        4,
        7,
        17,
        0,
        25,
        22,
        31,
        15,
        29,
        10,
        12,
        6,
        0,
        21,
        14,
        9,
        5,
        20,
        8,
        19,
        18]
    return lookup[(-x & x) % 37]


if __name__ == "__main__":
    print(countTrailingZero(48))

# Expected output:
4
# calculate 7 n / 8 without using division and multiplication operators | python program to evaluate ceil ( 7 n / 8 ) without using * and / ; note the inner bracket here . this is needed because precedence of ' - ' operator is higher than '<< ; 
def multiplyBySevenByEight(n):
    return (n - (n >> 3))


n = 9
print(multiplyBySevenByEight(n))

# Expected output:
8
# calculate 7 n / 8 without using division and multiplication operators | python3 program to evaluate 7 n / 8 without using * and / ; step 1 ) first multiply number by 7 i . e . 7 n = ( n << 3 ) - n step 2 ) divide result by 8 ; 
def multiplyBySevenByEight(n):
    return ((n << 3) - n) >> 3


n = 15
print(multiplyBySevenByEight(n))

# Expected output:
13
# longest set of palindrome numbers from the range [ l , r ] with at most k difference between its maximum and minimum | function to find the maximum size of group of palindrome numbers having difference between maximum and minimum element at most k ; stores the all the palindromic numbers in the range [ l , r ] ; traverse over the range [ l , r ] ; if i is a palindrome ; append the number in the list ; stores count of maximum palindromic numbers ; iterate each element in the list ; calculate rightmost index in the list < current element + k ; check if there is rightmost index from the current index ; return the count ; function to search the rightmost index of given number ; store the rightmost index ; calculate the mid ; if given number <= num ; assign ans = mid ; update low ; update high ; return ans ; function to check if the given number is palindrome or not ; generate reverse of the given number ; if n is a palindrome ; 
def search(list, num):
    low, high = 0, len(list) - 1
    ans = -1
    while (low <= high):
        mid = low + (high - low) // 2
        if (list[mid] <= num):
            ans = mid
            low = mid + 1
        else:
            high = mid - 1
    return ans


def isPalindrome(n):
    rev = 0
    temp = n
    while (n > 0):
        rev = rev * 10 + n % 10
        n //= 10
    return rev == temp

def countNumbers(L, R, K):
    list = []
    for i in range(L, R + 1):
        if (isPalindrome(i)):
            list .append(i)
    count = 0
    for i in range(len(list)):
        right_index = search(list, list[i] + K - 1)
        if (right_index != -1):
            count = max(count, right_index - i + 1)
    return count


if __name__ == '__main__':
    L, R = 98, 112
    K = 13
    print(countNumbers(L, R, K))

# Expected output:
3
# maximize sum possible by subtracting same value from all elements of a subarray of the given array | function to find the maximum sum by subtracting same value from all elements of a subarray ; stores previous smaller element ; stores next smaller element ; calculate contribution of each element ; return answer ; function to generate previous smaller element for each array element ; the first element has no previous smaller ; stack to keep track of elements that have occurred previously ; push the first index ; pop all the elements until the previous element is smaller than current element ; store the previous smaller element ; push the index of the current element ; return the array ; function to generate next smaller element for each array element ; stack to keep track of elements that have occurring next ; iterate in reverse order for calculating next smaller ; pop all the elements until the next element is smaller than current element ; store the next smaller element ; push the index of the current element ; return the array ; 
def findPrevious(a, n):
    ps = [0] * n
    ps[0] = -1
    stack = []
    stack .append(0)
    for i in range(1, n):
        while len(stack) > 0 and a[stack[-1]] >= a[i]:
            stack .pop()
        ps[i] = stack[-1]if len(stack) > 0 else -1
        stack .append(i)
    return ps


def findNext(a, n):
    ns = [0] * n
    ns[n - 1] = n
    stack = []
    stack .append(n - 1)
    for i in range(n - 2, -1, -1):
        while (len(stack) > 0 and a[stack[-1]] >= a[i]):
            stack .pop()
        ns[i] = stack[-1]if len(stack) > 0 else n
        stack .append(i)
    return ns

def findMaximumSum(a, n):
    prev_smaller = findPrevious(a, n)
    next_smaller = findNext(a, n)
    max_value = 0
    for i in range(n):
        max_value = max(max_value,
                        a[i] * (next_smaller[i] - prev_smaller[i] - 1))
    return max_value


n = 3
a = [80, 48, 82]
print(findMaximumSum(a, n))

# Expected output:
144
# check if the given string is shuffled substring of another string | ''this function returns true if contents of arr1[] and arr2[] are same, otherwise false. ; this function search for all permutations of pat [ ] in txt [ ] ; countp [ ] : store count of all characters of pattern counttw [ ] : store count of current window of text ; traverse through remaining characters of pattern ; compare counts of current window of text with counts of pattern [ ] ; add current character to current window ; remove the first character of previous window ; check for the last window in text ; 

MAX = 256


def compare(arr1, arr2):
    global MAX
    for i in range(MAX):
        if (arr1[i] != arr2[i]):
            return False
    return True


def search(pat, txt):
    M = len(pat)
    N = len(txt)
    countP = [0 for i in range(MAX)]
    countTW = [0 for i in range(MAX)]
    for i in range(M):
        countP[ord(pat[i])] += 1
        countTW[ord(txt[i])] += 1
    for i in range(M, N):
        if (compare(countP, countTW)):
            return True
        countTW[ord(txt[i])] += 1
        countTW[ord(txt[i - M])] -= 1
    if (compare(countP, countTW)):
        return True
        return False


txt = "BACDGABCDA"
pat = "ABCD"
if (search(pat, txt)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# maximize the median of the given array after adding k elements to the same array | function to return the maximized median ; sort the array ; if size is even ; if size is odd ; 
def getMaxMedian(arr, n, k):
    size = n + k
    arr .sort(reverse=False)
    if (size % 2 == 0):
        median = (arr[int(size / 2) - 1] + arr[int(size / 2)]) / 2
        return median
    median = arr[int(size / 2)]
    return median


if __name__ == '__main__':
    arr = [3, 2, 3, 4, 2]
    n = len(arr)
    k = 2
    print(getMaxMedian(arr, n, k))

# Expected output:
3
# sort 3 integers without using if condition or using only max ( ) function | python3 program to print three numbers in sorted order using max function ; find maximum element ; find minimum element ; 
def printSorted(a, b, c):
    get_max = max(a, max(b, c))
    get_min = -max(-a, max(-b, -c))
    get_mid = (a + b + c) - (get_max + get_min)
    print(get_min, " ", get_mid, " ", get_max)


a, b, c = 4, 1, 9
printSorted(a, b, c)

# Expected output:
1   4   9
# binary insertion sort | iterative implementation ; function to sort an array a [ ] of size 'n ; find location where selected should be inseretd ; move all elements after location to create space ; 
def binarySearch(a, item, low, high):
    while (low <= high):
        mid = low + (high - low) // 2
        if (item == a[mid]):
            return mid + 1
        elif (item > a[mid]):
            low = mid + 1
        else:
            high = mid - 1
    return low


def insertionSort(a, n):
    for i in range(n):
        j = i - 1
        selected = a[i]
        loc = binarySearch(a, selected, 0, j)
        while (j >= loc):
            a[j + 1] = a[j]
            j -= 1
        a[j + 1] = selected


a = [37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54]
n = len(a)
insertionSort(a, n)
print("Sorted array: ")
for i in range(n):
    print(a[i], end=" ")

# Expected output:
Sorted array: 
0 12 17 23 31 37 46 54 72 88 100
# insertion sort | function to do insertion sort ; move elements of arr [ 0. . i - 1 ] , that are greater than key , to one position ahead of their current position ; 
def insertionSort(arr):
    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1
        while j >= 0 and key < arr[j]:
            arr[j + 1] = arr[j]
            j -= 1
        arr[j + 1] = key


arr = [12, 11, 13, 5, 6]
insertionSort(arr)
for i in range(len(arr)):
    print("% d" % arr[i])

# Expected output:
 5
 6
 11
 12
 13
# count of distinct permutation of a string obtained by swapping only unequal characters | function to calculate total number of valid permutations ; creating count which is equal to the total number of characters present and ans that will store the number of unique permutations ; storing frequency of each character present in the string ; adding count of characters by excluding characters equal to current char ; reduce the frequency of the current character and count by 1 , so that it cannot interfere with the calculations of the same elements present to the right of it . ; return ans + 1 ( because the given string is also a unique permutation ) ; 
def validPermutations(str):
    m = {}
    count = len(str)
    ans = 0
    for i in range(len(str)):
        if (str[i] in m):
            m[str[i]] += 1
        else:
            m[str[i]] = 1
    for i in range(len(str)):
        ans += count - m[str[i]]
        m[str[i]] -= 1
        count -= 1
    return ans + 1


if __name__ == '__main__':
    str = "sstt"
    print(validPermutations(str))

# Expected output:
5
# counts paths from a point to reach origin | recursive function to count number of paths ; if we reach bottom or top left , we are have only one way to reach ( 0 , 0 ) ; else count sum of both ways ; 
def countPaths(n, m):
    if (n == 0 or m == 0):
        return 1
    return (countPaths(n - 1, m) + countPaths(n, m - 1))


n = 3
m = 2
print("Number of Paths", countPaths(n, m))

# Expected output:
Number of Paths 10
# check if two strings are same ignoring their cases | function to compare two strings ignoring their cases ; convert to uppercase ; if strings are equal , return true otherwise false ; function to print the same or not same if strings are equal or not equal ; 
def equalIgnoreCase(str1, str2):
    str1 = str1 .upper()
    str2 = str2 .upper()
    x = str1 == str2
    return x


def equalIgnoreCaseUtil(str1, str2):
    res = equalIgnoreCase(str1, str2)
    if (res):
        print("Same")
    else:
        print("Not Same")


if __name__ == "__main__":
    str1 = "Geeks"
    str2 = "geeks"
    equalIgnoreCaseUtil(str1, str2)
    str1 = "Geek"
    str2 = "geeksforgeeks"
    equalIgnoreCaseUtil(str1, str2)

# Expected output:
Same
Not Same
# replace every consonant sequence with its length in the given string | function to return the converted string after replacing every consonant sequence with its length ; to store the resultant string ; checking each character for consonant sequence ; count the length of consonants sequence ; add the length in the string ; add the vowel ; check for the last consonant sequence in the string ; return the resultant string ; 
def replaceConsonants(string):
    res = ""
    i = 0
    count = 0
    while (i < len(string)):
        if (string[i] != 'a' and string[i] != 'e' and string[i]
                != 'i' and string[i] != 'o' and string[i] != 'u'):
            i += 1
            count += 1
        else:
            if (count > 0):
                res += str(count)
            res += string[i]
            i += 1
            count = 0
    if (count > 0):
        res += str(count)
    return res


if __name__ == "__main__":
    string = "abcdeiop"
    print(replaceConsonants(string))

# Expected output:
a3eio1
# encrypt string with product of number of vowels and consonants in substring of size k | isvowel ( ) is a function that returns true for a vowel and false otherwise . ; function to encrypt the dtring ; for each substring ; substring of size k ; counting number of vowels and consonants ; append product to answer ; 
def isVowel(c):
    return (c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u')


def encryptString(s, n, k):
    countVowels = 0
    countConsonants = 0
    ans = ""
    for l in range(n - k + 1):
        countVowels = 0
        countConsonants = 0
        for r in range(l, l + k):
            if (isVowel(s[r])):
                countVowels += 1
            else:
                countConsonants += 1
        ans += (str)(countVowels * countConsonants)
    return ans


if __name__ == '__main__':
    s = "hello"
    n = len(s)
    k = 2
    print(encryptString(s, n, k))

# Expected output:
1101
# string containing first letter of every word in a given string with spaces | an efficient python3 implementation of above approach ; we are splitting the input based on spaces ( s ) + : this regular expression will handle scenarios where we have words separated by multiple spaces ; charat ( 0 ) will pick only the first character from the string and append to buffer ; 

charBuffer = []


def processWords(input):
    s = input .split(" ")
    for values in s:
        charBuffer .append(values[0])
    return charBuffer


if __name__ == '__main__':
    input = "geeks for geeks"
    print(*processWords(input), sep="")

# Expected output:
gfg
# generate all binary strings without consecutive 1 's | a utility function generate all string without consecutive 1 'sof size k ; print binary string without consecutive 1 's ; terminate binary string ; if previous character is '1' then we put only 0 at end of string example str = "01" then new string be "000" ; if previous character is '0' than we put both '1' and '0' at end of string example str = "00" then new string "001" and "000" ; function generate all binary string without consecutive 1 's ; base case ; one by one stores every binary string of length k ; generate all binary string starts with '0 ; generate all binary string starts with '1 ; 
def generateAllStringsUtil(K, str, n):
    if (n == K):
        print(*str[:n], sep="", end=" ")
        return
    if (str[n-1] == '1'):
        str[n] = '0'
        generateAllStringsUtil(K, str, n + 1)
    if (str[n-1] == '0'):
        str[n] = '0'
        generateAllStringsUtil(K, str, n + 1)
        str[n] = '1'
        generateAllStringsUtil(K, str, n + 1)


def generateAllStrings(K):
    if (K <= 0):
        return
    str = [0] * K
    str[0] = '0'
    generateAllStringsUtil(K, str, 1)
    str[0] = '1'
    generateAllStringsUtil(K, str, 1)


K = 3
generateAllStrings(K)

# Expected output:
000 001 010 100 101
# largest right circular cylinder within a cube | function to find the biggest right circular cylinder ; side cannot be negative ; radius of right circular cylinder ; height of right circular cylinder ; volume of right circular cylinder ; 
def findVolume(a):
    if (a < 0):
        return -1
    r = a / 2
    h = a
    V = 3.14 * pow(r, 2) * h
    return V


if __name__ == "__main__":
    a = 5
    print(findVolume(a))

# Expected output:
98.125
# program to find area of a trapezoid | function for the area ; 
def Area(b1, b2, h):
    return ((b1 + b2) / 2) * h


base1 = 8
base2 = 10
height = 6
area = Area(base1, base2, height)
print("Area is:", area)

# Expected output:
Area is: 54.0
# find number of diagonals in n sided convex polygon | ''python3 program to find number of diagonals in n sided convex polygon ; ''
def numberOfDiagonals(n):
    return n * (n - 3) / 2


def main():
    n = 5
    print(n, " sided convex polygon have ")
    print(numberOfDiagonals(n), " diagonals")


if __name__ == '__main__':
    main()

# Expected output:
5  sided convex polygon have 
5.0  diagonals
# area of the largest rectangle without a given point | function to find the maximum area such that it does not contains any hole ; area for all the possible positions of the cut ; find the maximum area among the above rectangles ; 
def maximumArea(l, b, x, y):
    left, right, above, below = 0, 0, 0, 0
    left = x * b
    right = (l - x - 1) * b
    above = l * y
    below = (b - y - 1) * l
    print(max(max(left, right), max(above, below)))


l = 8
b = 8
x = 0
y = 0
maximumArea(l, b, x, y)

# Expected output:
56
# minimize cost of removals required to make all remaining characters of the string unique | function to find the minimum cost of removing characters to make the string unique ; store the minimum cost required ; create a dictionary to store the maximum cost of removal a character ; create a dictionary to store the total deletion cost of a character ; traverse the string , s ; keep track of maximum cost of each character ; update the maximum deletion cost ; keep track of the total cost of each character ; update the total deletion cost ; traverse through all the unique characters ; keep the maximum cost character and delete the rest ; return the answer ; given string ; 
def delCost(s, cost):
    ans = 0
    forMax = {}
    forTot = {}
    for i in range(len(s)):
        if s[i]not in forMax:
            forMax[s[i]] = cost[i]
        else:
            forMax[s[i]] = max(cost[i], forMax[s[i]])
        if s[i]not in forTot:
            forTot[s[i]] = cost[i]
        else:
            forTot[s[i]] += cost[i]
    for i in forMax:
        ans += forTot[i] - forMax[i]
    return ans


string = "AAABBB"
cost = [1, 2, 3, 4, 5, 6]
print(delCost(string, cost))

# Expected output:
12
# smallest divisor of n closest to x | python3 program for the above approach ; stores divisors for all numbers in the vector divisors ; i is the divisor and j is the multiple ; function to compare the closeness of the given target ; function to find the element closest to target in divisors vector ; corner cases ; perform binary search ; check if target is less than the array element then search in left half ; check if target is greater than previous to mid , return closest of two ; repeat for left half ; check if target is greater than mid ; update i ; only single element left after search ; function to print the divisor of n closest to x ; function call to calculate and stores divisors of all numbers in a vector ; stores the closest value to target ; print the answer ; 

MAX = 10000
divisors = [[]for i in range(MAX + 1)]


def computeDivisors():
    global divisors
    global MAX
    for i in range(1, MAX + 1, 1):
        for j in range(i, MAX + 1, i):
            divisors[j].append(i)


def getClosest(val1, val2, target):
    if (target - val1 >= val2 - target):
        return val2
    else:
        return val1


def findClosest(arr, n, target):
    if (target <= arr[0]):
        return arr[0]
    if (target >= arr[n - 1]):
        return arr[n - 1]
    i = 0
    j = n
    mid = 0
    while (i < j):
        mid = (i + j) // 2
        if (arr[mid] == target):
            return arr[mid]
        if (target < arr[mid]):
            if (mid > 0 and target > arr[mid - 1]):
                return getClosest(arr[mid - 1], arr[mid], target)
            j = mid
        else:
            if (mid < n - 1 and target < arr[mid + 1]):
                return getClosest(arr[mid], arr[mid + 1], target)
            i = mid + 1
    return arr[mid]


def printClosest(N, X):
    global divisors
    computeDivisors()
    ans = findClosest(divisors[N], len(divisors[N]), X)
    print(ans)


if __name__ == '__main__':
    N = 16
    X = 5
    printClosest(N, X)

# Expected output:
4
# count elements of same value placed at same indices of two given arrays | function to count maximum matched elements from the arrays a [ ] and b [ ] ; stores position of elements of array a [ ] in the array b [ ] ; keep track of difference between the indices ; traverse the array a [ ] ; traverse the array b [ ] ; if difference is negative , add n to it ; keep track of the number of shifts required to place elements at same indices ; return the max matches ; 
def maxMatch(A, B):
    Aindex = {}
    diff = {}
    for i in range(len(A)):
        Aindex[A[i]] = i
    for i in range(len(B)):
        if i - Aindex[B[i]] < 0:
            if len(A) + i - Aindex[B[i]]not in diff:
                diff[len(A) + i - Aindex[B[i]]] = 1
            else:
                diff[len(A) + i - Aindex[B[i]]] += 1
        else:
            if i - Aindex[B[i]]not in diff:
                diff[i - Aindex[B[i]]] = 1
            else:
                diff[i - Aindex[B[i]]] += 1
    return max(diff .values())


A = [5, 3, 7, 9, 8]
B = [8, 7, 3, 5, 9]
print(maxMatch(A, B))

# Expected output:
3