giulio98/xlcost-single-prompt huggingface dataset:
# find all elements in array which have at | python3 program to find all elements in array which have at - least two greater elements itself . ; pick elements one by one and count greater elements . if count is more than 2 , print that element . ; 
def findElements(arr, n):
    for i in range(n):
        count = 0
        for j in range(0, n):
            if arr[j] > arr[i]:
                count = count + 1
        if count >= 2:
            print(arr[i], end=" ")


arr = [2, -6, 3, 5, 1]
n = len(arr)
findElements(arr, n)

# Expected output:
2 -6 1
# find all elements in array which have at | sorting based python 3 program to find all elements in array which have atleast two greater elements itself . ; 
def findElements(arr, n):
    arr .sort()
    for i in range(0, n - 2):
        print(arr[i], end=" ")


arr = [2, -6, 3, 5, 1]
n = len(arr)
findElements(arr, n)

# Expected output:
-6 1 2
# find all elements in array which have at | python3 program to find all elements in array which have atleast two greater elements itself . ; 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 ; 

import sys


def findElements(arr, n):
    first = -sys .maxsize
    second = -sys .maxsize
    for i in range(0, n):
        if (arr[i] > first):
            second = first
            first = arr[i]
        elif (arr[i] > second):
            second = arr[i]
    for i in range(0, n):
        if (arr[i] < second):
            print(arr[i], end=" ")


arr = [2, -6, 3, 5, 1]
n = len(arr)
findElements(arr, n)

# Expected output:
2 -6 1
# minimize count of increments of each element of subarrays required to make array non | function to find the minimum number of operations required to make the array non - increasing ; stores the count of required operations ; if arr [ i ] > arr [ i + 1 ] , no increments required . otherwise , add their difference to the answer ; return the result res ; 
def getMinOps(arr):
    res = 0
    for i in range(len(arr) - 1):
        res += max(arr[i + 1] - arr[i], 0)
    return res


arr = [1, 3, 4, 1, 2]
print(getMinOps(arr))

# Expected output:
4
# find the smallest missing number | function that returns smallest elements missing in a sorted array . ; left half has all elements from 0 to mid ; 
def findFirstMissing(array, start, end):
    if (start > end):
        return end + 1
    if (start != array[start]):
        return start
    mid = int((start + end) / 2)
    if (array[mid] == mid):
        return findFirstMissing(array, mid + 1, end)
    return findFirstMissing(array, start, mid)


arr = [0, 1, 2, 3, 4, 5, 6, 7, 10]
n = len(arr)
print("Smallest missing element is", findFirstMissing(arr, 0, n - 1))

# Expected output:
Smallest missing element is 8
# find the smallest missing number | function to find missing element ; index matches with value at that index , means missing element cannot be upto that point ; function to find smallest missing in sorted array ; check if 0 is missing in the array ; check is all numbers 0 to n - 1 are prsent in array ; 
def findFirstMissing(arr, start, end, first):
    if (start < end):
        mid = int((start + end) / 2)
        if (arr[mid] != mid + first):
            return findFirstMissing(arr, start, mid, first)
        else:
            return findFirstMissing(arr, mid + 1, end, first)
    return start + first


def findSmallestMissinginSortedArray(arr):
    if (arr[0] != 0):
        return 0
    if (arr[-1] == len(arr) - 1):
        return len(arr)
    first = arr[0]
    return findFirstMissing(arr, 0, len(arr) - 1, first)


arr = [0, 1, 2, 3, 4, 5, 7]
n = len(arr)
print("First Missing element is :", findSmallestMissinginSortedArray(arr))

# Expected output:
First Missing element is : 6
# maximum sum such that no two elements are adjacent | function to return max sum such that no two elements are adjacent ; current max excluding i ( no ternary in python ) ; current max including i ; return max of incl and excl ; 
def find_max_sum(arr):
    incl = 0
    excl = 0
    for i in arr:
        new_excl = excl if excl > incl else incl
        incl = excl + i
        excl = new_excl
    return (excl if excl > incl else incl)


arr = [5, 5, 10, 100, 10, 5]
print(find_max_sum(arr))

# Expected output:
110
# minimum steps to convert all top left to bottom right paths in matrix as palindrome | set 2 | function for counting minimum number of changes ; distance of elements from ( 0 , 0 ) will is i range [ 0 , n + m - 2 ] ; store frequencies of [ 0 , 9 ] at distance i initialize all with zero ; count frequencies of [ 0 , 9 ] ; increment frequency of value matrix [ i ] [ j ] at distance i + j ; find value with max frequency and count total cells at distance i from front end and rear end ; change all values to the value with max frequency ; return the answer ; 
def countChanges(matrix, n, m):
    dist = n + m - 1
    freq = [[0] * 10 for i in range(dist)]
    for i in range(n):
        for j in range(m):
            freq[i + j][matrix[i][j]] += 1
    min_changes_sum = 0
    for i in range(dist // 2):
        maximum = 0
        total_values = 0
        for j in range(10):
            maximum = max(maximum, freq[i][j] + freq[n + m - 2 - i][j])
            total_values += (freq[i][j] + freq[n + m - 2 - i][j])
        min_changes_sum += (total_values - maximum)
    return min_changes_sum


if __name__ == '__main__':
    mat = [[1, 2], [3, 5]]
    print(countChanges(mat, 2, 2))

# Expected output:
1
# lexicographically smallest array after at | modifies arr [ 0. . n - 1 ] to lexicographically smallest with k swaps . ; set the position where we we want to put the smallest integer ; if we exceed the max swaps then terminate the loop ; find the minimum value from i + 1 to max ( k or n ) ; swap the elements from minimum position we found till now to the i index ; set the final value after swapping pos - i elements ; 
def minimizeWithKSwaps(arr, n, k):
    for i in range(n - 1):
        pos = i
        for j in range(i + 1, n):
            if (j - i > k):
                break
            if (arr[j] < arr[pos]):
                pos = j
        for j in range(pos, i, -1):
            arr[j], arr[j - 1] = arr[j - 1], arr[j]
        k -= pos - i


n, k = 5, 3
arr = [7, 6, 9, 2, 1]
minimizeWithKSwaps(arr, n, k)
for i in range(n):
    print(arr[i], end=" ")

# Expected output:
2 7 6 9 1
# find maximum average subarray of k length | returns beginning index of maximum average subarray of length k ; check if ' k ' is valid ; create and fill array to store cumulative sum . csum [ i ] stores sum of arr [ 0 ] to arr [ i ] ; initialize max_sm as sum of first subarray ; find sum of other subarrays and update max_sum if required . ; return starting index ; 
def findMaxAverage(arr, n, k):
    if k > n:
        return -1
    csum = [0] * n
    csum[0] = arr[0]
    for i in range(1, n):
        csum[i] = csum[i - 1] + arr[i]
    max_sum = csum[k - 1]
    max_end = k - 1
    for i in range(k, n):
        curr_sum = csum[i] - csum[i - k]
        if curr_sum > max_sum:
            max_sum = curr_sum
            max_end = i
    return max_end - k + 1


arr = [1, 12, -5, -6, 50, 3]
k = 4
n = len(arr)
print("The maximum average subarray of length", k,
      "begins at index", findMaxAverage(arr, n, k))

# Expected output:
The maximum average subarray of length 4 begins at index 1
# find maximum average subarray of k length | returns beginning index of maximum average subarray of length k ; check if ' k ' is valid ; compute sum of first ' k ' elements ; compute sum of remaining subarrays ; return starting index ; 
def findMaxAverage(arr, n, k):
    if (k > n):
        return -1
    sum = arr[0]
    for i in range(1, k):
        sum += arr[i]
    max_sum = sum
    max_end = k - 1
    for i in range(k, n):
        sum = sum + arr[i] - arr[i - k]
        if (sum > max_sum):
            max_sum = sum
            max_end = i
    return max_end - k + 1


arr = [1, 12, -5, -6, 50, 3]
k = 4
n = len(arr)
print("The maximum average subarray of length", k,
      "begins at index", findMaxAverage(arr, n, k))

# Expected output:
The maximum average subarray of length 4 begins at index 1
# minimum score possible for a player by selecting one or two consecutive array elements from given binary array | stores the minimum score for each states as map < pair < pos , myturn > , ans > ; function to find the minimum score after choosing element from array ; return the stored state ; base case ; player a 's turn ; find the minimum score ; store the current state ; return the result ; player b 's turn ; find minimum score ; store the current state ; return the result ; function that finds the minimum penality after choosing element from the given binary array ; starting position of choosing element from array ; 0 denotes player a turn 1 denotes player b turn ; function call ; print the answer for player a and b ; minimum penalty ; calculate sum of all arr elements ; print the minimum score ; 

m = dict()


def findMinimum(a, n, pos, myturn):
    if (pos, myturn) in m:
        return m[(pos, myturn)]
    if (pos >= n - 1):
        return 0
    if (not myturn):
        ans = min(findMinimum(a, n, pos + 1, not myturn) +
                  a[pos], findMinimum(a, n, pos + 2, not myturn) + a[pos] + a[pos + 1])
        m[(pos, myturn)] = ans
        return ans
    if (myturn):
        ans = min(
            findMinimum(
                a,
                n,
                pos + 1,
                not myturn),
            findMinimum(
                a,
                n,
                pos + 2,
                not myturn))
        m[(pos, myturn)] = ans
        return ans
    return 0


def countPenality(arr, N):
    pos = 0
    turn = False
    return findMinimum(arr, N, pos, turn) + 1


def printAnswer(arr, N):
    a = countPenality(arr, N)
    sum = 0
    for i in range(N):
        sum += arr[i]
    print(a)


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

# Expected output:
2
# count the number of ways to construct the target string | python 3 program to count the number of ways to construct the target string ; base case ; if current subproblem has been solved , use the value ; current character ; search through all the indiced at which the current character occurs . for each index greater than prev , take the index and move to the next position , and add to the answer . ; store and return the solution for this subproblem ; preprocess the strings by storing for each character of every string , the index of their occurrence we will use a common list for all because of only the index matter in the string from which the character was picked ; we are storing j + 1 because the initial picked index in the recursive step will ne 0. this is just for ease of implementation ; initialise dp table . - 1 represents that the subproblem hasn 't been solve ; 

mod = 1000000007
dp = [[-1 for i in range(1000)]for j in range(1000)]


def calculate(pos, prev, s, index):
    if (pos == len(s)):
        return 1
    if (dp[pos][prev] != -1):
        return dp[pos][prev]
    c = ord(s[pos]) - ord('a')
    answer = 0
    for i in range(len(index)):
        if (index[i] > prev):
            answer = (answer % mod + calculate(pos + 1,
                      index[i], s, index) % mod) % mod
    dp[pos][prev] = 4
    return dp[pos][prev]


def countWays(a, s):
    n = len(a)
    index = [[]for i in range(26)]
    for i in range(n):
        for j in range(len(a[i])):
            index[ord(a[i][j]) - ord('a')].append(j + 1)
    return calculate(0, 0, s, index[0])


if __name__ == '__main__':
    A = []
    A .append("adc")
    A .append("aec")
    A .append("erg")
    S = "ac"
    print(countWays(A, S))

# Expected output:
4
# double knapsack | dynamic programming | w1_r represents remaining capacity of 1 st knapsack w2_r represents remaining capacity of 2 nd knapsack i represents index of the array arr we are working on ; base case ; variables to store the result of three parts of recurrence relation ; store the state in the 3d array ; 
def maxWeight(arr, n, w1_r, w2_r, i):
    if i == n:
        return 0
    if dp[i][w1_r][w2_r] != -1:
        return dp[i][w1_r][w2_r]
    fill_w1, fill_w2, fill_none = 0, 0, 0
    if w1_r >= arr[i]:
        fill_w1 = arr[i] + maxWeight(arr, n, w1_r - arr[i], w2_r, i + 1)
    if w2_r >= arr[i]:
        fill_w2 = arr[i] + maxWeight(arr, n, w1_r, w2_r - arr[i], i + 1)
    fill_none = maxWeight(arr, n, w1_r, w2_r, i + 1)
    dp[i][w1_r][w2_r] = max(fill_none, max(fill_w1, fill_w2))
    return dp[i][w1_r][w2_r]


if __name__ == "__main__":
    arr = [8, 2, 3]
    maxN, maxW = 31, 31
    dp = [[[-1] * maxW] * maxW] * maxN
    n = len(arr)
    w1, w2 = 10, 3
    print(maxWeight(arr, n, w1, w2, 0))

# Expected output:
13
# maximum size subset with given sum | a dynamic programming solution for subset sum problem + maximal subset value . returns size of maximum sized subset if there is a subset of set [ ] with sun equal to given sum . it returns - 1 if there is no subset with given sum . ; the value of subset [ i ] [ j ] will be true if there is a subset of set [ 0. . j - 1 ] with sum equal to i ; if sum is 0 , then answer is true ; if sum is not 0 and set is empty , then answer is false ; fill the subset table in bottom up manner ; 
def isSubsetSum(arr, n, sum):
    subset = [[False for x in range(n + 1)]for y in range(sum + 1)]
    count = [[0 for x in range(n + 1)]for y in range(sum + 1)]
    for i in range(n + 1):
        subset[0][i] = True
        count[0][i] = 0
    for i in range(1, sum + 1):
        subset[i][0] = False
        count[i][0] = -1
    for i in range(1, sum + 1):
        for j in range(1, n + 1):
            subset[i][j] = subset[i][j - 1]
            count[i][j] = count[i][j - 1]
            if (i >= arr[j - 1]):
                subset[i][j] = (subset[i][j] or subset[i - arr[j - 1]][j - 1])
                if (subset[i][j]):
                    count[i][j] = (
                        max(count[i][j - 1], count[i - arr[j - 1]][j - 1] + 1))
    return count[sum][n]


if __name__ == "__main__":
    arr = [2, 3, 5, 10]
    sum = 20
    n = 4
    print(isSubsetSum(arr, n, sum))

# Expected output:
4
# print all longest common sub | python3 program to find all lcs of two strings in sorted order . ; dp matrix to store result of sub calls for lcs ; a memoization based function that returns lcs of str1 [ i . . len1 - 1 ] and str2 [ j . . len2 - 1 ] ; base condition ; if lcs has been computed ; if characters are same return previous + 1 else max of two sequences after removing i ' th ▁ and ▁ j ' th char one by one ; function to prall routes common sub - sequences of length lcslen ; if currlcs is equal to lcslen then prit ; if we are done with all the characters of both string ; here we have to prall sub - sequences lexicographically , that ' s ▁ why ▁ we ▁ start ▁ from ▁ ' a ' to ' z ' if this character is  present in both of them then append it in data[] and same  remaining part ; done is a flag to tell that we have printed all the subsequences corresponding to current character ; if character ch is present in str1 then check if it is present in str2 ; if ch is present in both of them and remaining length is equal to remaining lcs length then add ch in sub - sequenece ; if we found lcs beginning with current character . ; this function prints all lcs of str1 and str2 in lexicographic order . ; find lengths of both strings ; find length of lcs ; prall lcs using recursive backtracking data [ ] is used to store individual lcs . ; 

MAX = 100
lcslen = 0


dp = [[-1 for i in range(MAX)] for i in range(MAX)]


def lcs(str1, str2, len1, len2, i, j):
    if (i == len1 or j == len2):
        dp[i][j] = 0
        return dp[i][j]
    if (dp[i][j] != -1):
        return dp[i][j]

    ret = 0
    if (str1[i] == str2[j]):
        ret = 1 + lcs(str1, str2, len1, len2, i + 1, j + 1)
    else:
        ret = max(lcs(str1, str2, len1, len2, i + 1, j),
                  lcs(str1, str2, len1, len2, i, j + 1))
    dp[i][j] = ret
    return ret


def printAll(str1, str2, len1, len2, data, indx1, indx2, currlcs):
    if (currlcs == lcslen):
        print("".join(data[:currlcs]))
        return
    if (indx1 == len1 or indx2 == len2):
        return
    for ch in range(ord('a'), ord('z') + 1):
        done = False

        for i in range(indx1, len1):
            if (chr(ch) == str1[i]):
                for j in range(indx2, len2):
                    if (chr(ch) == str2[j] and dp[i][j] == lcslen-currlcs):
                        data[currlcs] = chr(ch)
                        printAll(str1, str2, len1, len2, data,
                                 i + 1, j + 1, currlcs + 1)
                        done = True
                        break
            if (done):
                break


def prinlAllLCSSorted(str1, str2):
    global lcslen
    len1, len2 = len(str1), len(str2)

    lcslen = lcs(str1, str2, len1, len2, 0, 0)
    data = ['a' for i in range(MAX)]
    printAll(str1, str2, len1, len2, data, 0, 0, 0)


if __name__ == '__main__':
    str1 = "abcabcaa"
    str2 = "acbacba"
    prinlAllLCSSorted(str1, str2)

# Expected output:
ababa
abaca
abcba
acaba
acaca
acbaa
acbca
# check for majority element in a sorted array | python3 program to check for majority element in a sorted array ; get last index according to n ( even or odd ) ; search for first occurrence of x in arr [ ] ; check if x is present and is present more than n / 2 times ; 
def isMajority(arr, n, x):
    last_index = (n // 2 + 1)if n % 2 == 0 else (n // 2)
    for i in range(last_index):
        if arr[i] == x and arr[i + n // 2] == x:
            return 1


arr = [1, 2, 3, 4, 4, 4, 4]
n = len(arr)
x = 4
if (isMajority(arr, n, x)):
    print("% d appears more than % d times in arr[]" % (x, n // 2))
else:
    print("% d does not appear more than % d times in arr[]" % (x, n // 2))

# Expected output:
 4 does not appear more than  3 times in arr[]
# check for majority element in a sorted array |  ; 
def isMajorityElement(arr, n, key):
    if (arr[n // 2] == key):
        return True
    return False


if __name__ == "__main__":
    arr = [1, 2, 3, 3, 3, 3, 10]
    n = len(arr)
    x = 3
    if (isMajorityElement(arr, n, x)):
        print(x, " appears more than ", n // 2, " times in arr[]")
    else:
        print(x, " does not appear more than", n // 2, " times in arr[]")

# Expected output:
3  appears more than  3  times in arr[]
# cutting a rod | dp | a dynamic programming solution for rod cutting problem ; returns the best obtainable price for a rod of length n and price [ ] as prices of different pieces ; build the table val [ ] in bottom up manner and return the last entry from the table ; 

INT_MIN = -32767


def cutRod(price, n):
    val = [0 for x in range(n + 1)]
    val[0] = 0
    for i in range(1, n + 1):
        max_val = INT_MIN
        for j in range(i):
            max_val = max(max_val, price[j] + val[i - j - 1])
        val[i] = max_val
    return val[n]


arr = [1, 5, 8, 9, 10, 17, 17, 20]
size = len(arr)
print("Maximum Obtainable Value is " + str(cutRod(arr, size)))

# Expected output:
Maximum Obtainable Value is 22
# modify array to another given array by replacing array elements with the sum of the array | function to check if the arr [ ] can be converted to target [ ] by replacing any element in arr [ ] by the sum of arr [ ] ; store the maximum element ; store the index of the maximum element ; traverse the array target [ ] ; if current element is greater than max ; if max element is 1 ; traverse the array , target [ ] ; if current index is not equal to maximum element index ; update max ; if max is less than or equal to 0 , ; update the maximum element ; recursively call the function ; 
def isPossible(target):
    max = 0
    index = 0
    for i in range(len(target)):
        if (max < target[i]):
            max = target[i]
            index = i
    if (max == 1):
        return True
    for i in range(len(target)):
        if (i != index):
            max -= target[i]
        if (max <= 0):
            return False
    target[index] = max
    return isPossible(target)


target = [9, 3, 5]
res = isPossible(target)
if (res):
    print("YES")
else:
    print("NO")

# Expected output:
YES
# sum of all products of the binomial coefficients of two numbers up to k | function returns ncr i . e . binomial coefficient ; initialize res with 1 ; since c ( n , r ) = c ( n , n - r ) ; evaluating expression ; 
def nCr(n, r):
    res = 1
    if (r > n - r):
        r = n - r
    for i in range(r):
        res *= (n - i)
        res //= (i + 1)
    return res


if __name__ == '__main__':
    n = 3
    m = 2
    k = 2
    print(nCr(n + m, k))

# Expected output:
10
# check if n can be obtained from 1 by repetitively multiplying by 10 or 20 | python program to check if n can be obtained from 1 by repetitive multiplication by 10 or 20 ; function to check if n can be obtained or not ; count and remove trailing zeroes ; check if remaining n is a power of 2 ; to check the condition to print yes or no ; 

import math


def Is_possible(N):
    C = 0
    D = 0
    while (N % 10 == 0):
        N = N / 10
        C += 1
    if (math .log(N, 2) - int(math .log(N, 2)) == 0):
        D = int(math .log(N, 2))
        if (C >= D):
            print("YES")
        else:
            print("NO")
    else:
        print("NO")


N = 2000000000000
Is_possible(N)

# Expected output:
YES
# central polygonal numbers | function to find n - th term in the series ; 
def findNthTerm(n):
    print(n * n - n + 1)


N = 4
findNthTerm(N)

# Expected output:
13
# program to print the series 1 , 3 , 4 , 8 , 15 , 27 , 50 â €¦ till n terms | function to print the series ; generate the ith term and print it ; 
def printSeries(n, a, b, c):
    if (n == 1):
        print(a, end=" ")
        return
    if (n == 2):
        print(a, b, end=" ")
        return
    print(a, b, c, end=" ")
    for i in range(4, n + 1):
        d = a + b + c
        print(d, end=" ")
        a = b
        b = c
        c = d


N = 7
a = 1
b = 3
c = 4
printSeries(N, a, b, c)

# Expected output:
1 3 4 8 15 27 50
# diameter of a binary indexed tree with n nodes | function to find diameter of bit with n + 1 nodes ; l is size of subtree just before subtree in which n lies ; h is the height of subtree just before subtree in which n lies ; base cases ; size of subtree are power of 2 ; 3 cases as explained in approach ; 
def diameter(n):
    L, H, templen = 0, 0, 0
    L = 1
    H = 0
    if (n == 1):
        return 1
    if (n == 2):
        return 2
    if (n == 3):
        return 3
    while (L * 2 <= n):
        L *= 2
        H += 1
    if (n >= L * 2 - 1):
        return 2 * H + 1
    elif (n >= L + (L / 2) - 1):
        return 2 * H
    return 2 * H - 1


n = 15
print(diameter(n))

# Expected output:
7
# find the larger exponential among two exponentials | python3 implementation of the approach ; function to find whether a ^ b is greater or c ^ d ; find b * log ( a ) ; find d * log ( c ) ; compare both values ; 

import math


def compareValues(a, b, c, d):
    log1 = math .log10(a)
    num1 = log1 * b
    log2 = math .log10(c)
    num2 = log2 * d
    if num1 > num2:
        print(a, '^', b)
    else:
        print(c, '^', d)


a = 8
b = 29
c = 60
d = 59
compareValues(a, b, c, d)

# Expected output:
60 ^ 59