giulio98/xlcost-single-prompt huggingface dataset:
# count of numbers of length n having prime numbers at odd indices and odd numbers at even indices | python program for above approach ; no of odd indices in n - digit number ; no of even indices in n - digit number ; no of ways of arranging prime number digits in odd indices ; no of ways of arranging odd number digits in even indices ; returning the total number of ways ; 
def count(N):
    odd_indices = N // 2
    even_indices = N // 2 + N % 2
    arrange_odd = 4 ** odd_indices
    arrange_even = 5 ** even_indices
    return arrange_odd * arrange_even


if __name__ == "__main__":
    N = 4
    print(count(N))

# Expected output:
400
# check if a given array is sorted in spiral manner or not | function to check if the array is spirally sorted or not ; stores start index of the array ; stores end index of an array ; if arr [ start ] greater than arr [ end ] ; update start ; if arr [ end ] greater than arr [ start ] ; update end ; 
def isSpiralSorted(arr, n):
    start = 0
    end = n - 1
    while (start < end):
        if (arr[start] > arr[end]):
            return False
        start += 1
        if (arr[end] > arr[start]):
            return False
        end -= 1
    return True


if __name__ == "__main__":
    arr = [1, 10, 14, 20, 18, 12, 5]
    N = len(arr)
    if (isSpiralSorted(arr, N)):
        print("YES")
    else:
        print("NO")

# Expected output:
YES
# print all strings from given array that can be typed using keys from a single row of a qwerty keyboard | function to print all strings that can be typed using keys of a single row in a qwerty keyboard ; stores row number of all possible character of the strings ; traverse the array ; if current string is not an empty string ; sets true / false if a string can be typed using keys of a single row or not ; stores row number of the first character of current string ; stores length of word ; traverse current string ; if current character can 't be  typed using keys of rownum only ; update flag ; if current string can be typed using keys from rownum only ; print the string ; 
def findWordsSameRow(arr):
    mp = {'q': 1, 'w': 1, 'e': 1, 'r': 1,
          't': 1, 'y': 1, 'u': 1, 'o': 1,
          'p': 1, 'i': 1, 'a': 2, 's': 2,
          'd': 2, 'f': 2, 'g': 2, 'h': 2,
          'j': 2, 'k': 2, 'l': 2, 'z': 3,
          'x': 3, 'c': 3, 'v': 3, 'b': 3,
          'n': 3, 'm': 3}
    for word in arr:
        if (len(word) != 0):
            flag = True

            rowNum = mp[word[0].lower()]
            M = len(word)
            for i in range(1, M):
                if (mp[word[i].lower()] != rowNum):
                    flag = False
                    break
            if (flag):
                print(word, end=' ')


words = ["Yeti", "Had", "GFG", "comment"]

findWordsSameRow(words)

# Expected output:
Yeti Had GFG
# count quadruples of given type from given array | python3 program of the above approach ; function to find the count of the subsequence of given type ; stores the count of quadruples ; generate all possible combinations of quadruples ; check if 1 st element is equal to 3 rd element ; check if 2 nd element is equal to 4 th element ; 

maxN = 2002


def countSubsequece(a, n):
    answer = 0
    for i in range(n):
        for j in range(i + 1, n):
            for k in range(j + 1, n):
                for l in range(k + 1, n):
                    if (a[j] == a[l] and a[i] == a[k]):
                        answer += 1
    return answer


if __name__ == '__main__':
    a = [1, 2, 3, 2, 1, 3, 2]
    print(countSubsequece(a, 7))

# Expected output:
5
# smallest character in a string having minimum sum of distances between consecutive repetitions | python3 program for the above approach ; function to find the character repeats with minimum distance ; stores the first and last index ; intialize with - 1 ; get the values of last and first occurence ; update the first index ; update the last index ; intialize the min ; get the minimum ; values must not be same ; update the minimum distance ; return ans ; 

import sys


def minDistChar(s):
    n = len(s)
    first = []
    last = []
    for i in range(26):
        first .append(-1)
        last .append(-1)
    for i in range(n):
        if (first[ord(s[i]) - ord('a')] == -1):
            first[ord(s[i]) - ord('a')] = i
        last[ord(s[i]) - ord('a')] = i
    min = sys .maxsize
    ans = '1'
    for i in range(26):
        if (last[i] == first[i]):
            continue
        if (min > last[i] - first[i]):
            min = last[i] - first[i]
            ans = i + ord('a')
    return chr(ans)


if __name__ == "__main__":
    str = "geeksforgeeks"
    print(minDistChar(str))

# Expected output:
g
# minimum steps required to reach the end of a matrix | set 2 | python 3 implementation of the approach ; function to return the minimum steps required to reach the end of the matrix ; array to determine whether a cell has been visited before ; queue for bfs ; to store the depth of search ; bfs algorithm ; current queue size ; top - most element of queue ; to store index of cell for simplicity ; base case ; if we reach ( n - 1 , n - 1 ) ; marking the cell visited ; pushing the adjacent cells in the queue that can be visited from the current cell ; 

n = 3


def minSteps(arr):
    v = [[0 for i in range(n)]for j in range(n)]
    q = [[0, 0]]
    depth = 0
    while (len(q) != 0):
        x = len(q)
        while (x > 0):
            y = q[0]
            i = y[0]
            j = y[1]
            q .remove(q[0])
            x -= 1
            if (v[i][j]):
                continue
            if (i == n - 1 and j == n - 1):
                return depth
            v[i][j] = 1
            if (i + arr[i][j] < n):
                q .append([i + arr[i][j], j])
            if (j + arr[i][j] < n):
                q .append([i, j + arr[i][j]])
        depth += 1
    return -1


if __name__ == '__main__':
    arr = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
    print(minSteps(arr))

# Expected output:
4
# largest gap in an array | a python 3 program to find largest gap between two elements in an array . ; function to solve the given problem ; 

import sys


def solve(a, n):
    max1 = -sys .maxsize - 1
    for i in range(0, n, 1):
        for j in range(0, n, 1):
            if (abs(a[i] - a[j]) > max1):
                max1 = abs(a[i] - a[j])
    return max1


if __name__ == '__main__':
    arr = [-1, 2, 3, -4, -10, 22]
    size = len(arr)
    print("Largest gap is :", solve(arr, size))

# Expected output:
Largest gap is : 32
# largest gap in an array | function to solve the given problem ; finding maximum and minimum of an array ; 
def solve(a, n):
    min1 = a[0]
    max1 = a[0]
    for i in range(n):
        if (a[i] > max1):
            max1 = a[i]
        if (a[i] < min1):
            min1 = a[i]
    return abs(min1 - max1)


if __name__ == "__main__":
    arr = [-1, 2, 3, 4, -10]
    size = len(arr)
    print("Largest gap is : ", solve(arr, size))

# Expected output:
Largest gap is :  14
# print reverse string after removing vowels | function for replacing the string ; initialize a string of length n ; traverse through all characters of string ; assign the value to string r from last index of string s ; if s [ i ] is a consonant then print r [ i ] ; 
def replaceOriginal(s, n):
    r = [' '] * n
    for i in range(n):
        r[i] = s[n - 1 - i]
        if (s[i] != 'a' and s[i] != 'e' and
            s[i] != 'i' and s[i] != 'o' and
                s[i] != 'u'):
            print(r[i], end="")
    print()


if __name__ == "__main__":
    s = "geeksforgeeks"
    n = len(s)
    replaceOriginal(s, n)

# Expected output:
segrfseg
# check if a string can be made equal to another string by swapping or replacement of characters | function to find if given strings are same or not ; base condition ; stores frequency of characters of the str1 and str2 ; traverse strings str1 & str2 and store frequencies in a [ ] and b [ ] ; check if both strings have same characters or not ; if a character is present in one and is not in another string , return false ; sort the array a [ ] and b [ ] ; check arrays a and b contain the same frequency or not ; if the frequencies are not the same after sorting ; at this point , str1 can be converted to str2 ; 
def sameStrings(str1, str2):
    N = len(str1)
    M = len(str2)
    if (N != M):
        return False
    a, b = [0] * 256, [0] * 256
    for i in range(N):
        a[ord(str1[i]) - ord('a')] += 1
        b[ord(str2[i]) - ord('a')] += 1
    i = 0
    while (i < 256):
        if ((a[i] == 0 and b[i] == 0) or (a[i] != 0 and b[i] != 0)):
            i += 1
        else:
            return False
    a = sorted(a)
    b = sorted(b)
    for i in range(256):
        if (a[i] != b[i]):
            return False
    return True


if __name__ == '__main__':
    S1, S2 = "cabbba", "abbccc"
    if (sameStrings(S1, S2)):
        print("YES")
    else:
        print("NO")

# Expected output:
YES
# reduce given three numbers by decrementing in pairs | function to find the minimum number operations ; insert the three numbers in array ; sort the array ; case 2 ; case 1 ; 
def solution(A, B, C):
    arr = [0] * 3
    arr[0] = A
    arr[1] = B
    arr[2] = C
    arr = sorted(arr)
    if (arr[2] < arr[0] + arr[1]):
        return ((arr[0] + arr[1] + arr[2]) // 2)
    else:
        return (arr[0] + arr[1])


if __name__ == '__main__':
    A = 8
    B = 1
    C = 5
    print(solution(A, B, C))

# Expected output:
6
# search an element in a sorted and rotated array with duplicates | function to return the index of the key in arr [ l . . h ] if the key is present otherwise return - 1 ; the tricky case , just update left and right ; if arr [ l ... mid ] is sorted ; as this subarray is sorted , we can quickly check if key lies in any of the halves ; if key does not lie in the first half subarray then divide the other half into two subarrays such that we can quickly check if key lies in the other half ; if arr [ l . . mid ] first subarray is not sorted then arr [ mid ... h ] must be sorted subarray ; 
def search(arr, l, h, key):
    if (l > h):
        return -1
    mid = (l + h) // 2
    if (arr[mid] == key):
        return mid
    if ((arr[l] == arr[mid]) and (arr[h] == arr[mid])):
        l += 1
        h -= 1
        return search(arr, l, h, key)
    if (arr[l] <= arr[mid]):
        if (key >= arr[l] and key <= arr[mid]):
            return search(arr, l, mid - 1, key)
        return search(arr, mid + 1, h, key)
    if (key >= arr[mid] and key <= arr[h]):
        return search(arr, mid + 1, h, key)
    return search(arr, l, mid - 1, key)


if __name__ == "__main__":
    arr = [3, 3, 1, 2, 3, 3]
    n = len(arr)
    key = 3
    print(search(arr, 0, n - 1, key))

# Expected output:
4
# case | function to return the sorted string ; vectors to store the lowercase and uppercase characters ; sort both the vectors ; if current character is lowercase then pick the lowercase character from the sorted list ; else pick the uppercase character ; return the sorted string ; 
def getSortedString(s, n):
    v1 = []
    v2 = []
    for i in range(n):
        if (s[i] >= 'a' and s[i] <= 'z'):
            v1 .append(s[i])
        if (s[i] >= 'A' and s[i] <= 'Z'):
            v2 .append(s[i])
    v1 = sorted(v1)
    v2 = sorted(v2)
    i = 0
    j = 0
    for k in range(n):
        if (s[k] >= 'a' and s[k] <= 'z'):
            s[k] = v1[i]
            i += 1
        elif (s[k] >= 'A' and s[k] <= 'Z'):
            s[k] = v2[j]
            j += 1
    return "".join(s)


s = "gEeksfOrgEEkS"
ss = [i for i in s]
n = len(ss)
print(getSortedString(ss, n))

# Expected output:
eEfggkEkrEOsS
# check if the string contains consecutive letters and each letter occurs exactly once | function to check if the condition holds ; get the length of the string ; sort the given string ; iterate for every index and check for the condition ; if are not consecutive ; 
def check(s):
    l = len(s)
    s = ''.join(sorted(s))
    for i in range(1, l):
        if ord(s[i]) - ord(s[i - 1]) != 1:
            return False
    return True


if __name__ == "__main__":
    string = "dcef"
    if check(string):
        print("Yes")
    else:
        print("No")
    string = "xyza"
    if check(string):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
No
# smallest subset with sum greater than all other elements | function to find minimum elements needed . ; calculating half of array sum ; sort the array in descending order . ; current sum greater than sum ; 
def minElements(arr, n):
    halfSum = 0
    for i in range(n):
        halfSum = halfSum + arr[i]
    halfSum = int(halfSum / 2)
    arr .sort(reverse=True)
    res = 0
    curr_sum = 0
    for i in range(n):
        curr_sum += arr[i]
        res += 1
        if curr_sum > halfSum:
            return res
    return res


arr = [3, 1, 7, 1]
n = len(arr)
print(minElements(arr, n))

# Expected output:
1
# minimum increment and decrement by k of each pair elements required to make all array elements equal | function to check if its possible to make all array elements equal or not ; stores the sum of the array ; traverse the array ; if sum is divisible by n ; otherwise , not possible to make all array elements equal ; 
def arrayElementEqual(arr, N):
    sum = 0
    for i in range(N):
        sum += arr[i]
    if (sum % N == 0):
        print('Yes')
    else:
        print("No")


arr = [1, 5, 6, 4]
N = len(arr)
arrayElementEqual(arr, N)

# Expected output:
Yes
# rearrange array to maximize sum of gcd of array elements with their respective indices | function to find the maximum sum of gcd ( arr [ i ] , i ) by rearranging the array ; stores maximum sum of gcd ( arr [ i ] , i ) by rearranging the array elements ; update res ; 
def findMaxValByRearrArr(arr, N):
    res = 0
    res = (N * (N + 1)) // 2
    return res


if __name__ == '__main__':
    arr = [3, 2, 1]
    N = len(arr)
    print(findMaxValByRearrArr(arr, N))

# Expected output:
6
# polygon with maximum sides that can be inscribed in an n | function to find the maximum sided polygon that can be inscribed ; base case ; return n / 2 if n is even otherwise , return - 1 ; 
def MaximumSides(n):
    if (n < 4):
        return -1
    if n % 2 == 0:
        return n // 2
    return -1


if __name__ == '__main__':
    N = 8
    print(MaximumSides(N))

# Expected output:
4
# mean of array generated by products of all pairs of the given array | function to find the mean of pair product array of arr [ ] ; initializing suffix sum array ; build suffix sum array ; size of pairproductarray ; stores sum of pairproductarray ; store the mean ; find mean of pairproductarray ; return the resultant mean ; 
def pairProductMean(arr, N):
    suffixSumArray = [0] * N
    suffixSumArray[N - 1] = arr[N - 1]
    for i in range(N - 2, -1, -1):
        suffixSumArray[i] = suffixSumArray[i + 1] + arr[i]
    length = (N * (N - 1)) // 2
    res = 0
    for i in range(N - 1):
        res += arr[i] * suffixSumArray[i + 1]
    mean = 0
    if (length != 0):
        mean = res / length
    else:
        mean = 0
    return mean


if __name__ == '__main__':
    arr = [1, 2, 4, 8]
    N = len(arr)
    print(round(pairProductMean(arr, N), 2))

# Expected output:
11.67
# minimize count of unique paths from top left to bottom right of a matrix by placing k 1 s | function to return the value of binomial coefficient c ( n , k ) ; since c ( n , k ) = c ( n , n - k ) ; calculate the value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- -- * 1 ] ; function to find the minimum count of paths from top left to bottom right by placing k 1 s in the matrix ; count of ways without 1 s ; count of paths from starting poto mid point ; count of paths from mid poto end point ; 
def ncr(n, k):
    res = 1
    if (k > n - k):
        k = n - k
    for i in range(k):
        res *= (n - i)
        res //= (i + 1)
    return res


def countPath(N, M, K):
    answer = 0
    if (K >= 2):
        answer = 0
    elif (K == 0):
        answer = ncr(N + M - 2, N - 1)
    else:
        answer = ncr(N + M - 2, N - 1)
        X = (N - 1) // 2 + (M - 1) // 2
        Y = (N - 1) // 2
        midCount = ncr(X, Y)
        X = ((N - 1) - (N - 1) // 2)+((M - 1) - (M - 1) // 2)
        Y = ((N - 1) - (N - 1) // 2)
        midCount *= ncr(X, Y)
        answer -= midCount
    return answer


if __name__ == '__main__':
    N = 3
    M = 3
    K = 1
    print(countPath(N, M, K))

# Expected output:
2
# maximum number of operations required such that no pairs from a matrix overlap | function to find maximum count of operations ; initialize count by 0 ; iterate over remaining pairs ; check if first operation is applicable ; check if 2 nd operation is applicable ; otherwise ; return the count of operations ; 
def find_max(v, n):
    count = 0
    if (n >= 2):
        count = 2
    else:
        count = 1
    for i in range(1, n - 1):
        if (v[i - 1][0] > (v[i][0] + v[i][1])):
            count += 1
        elif (v[i + 1][0] > (v[i][0] + v[i][1])):
            count += 1
            v[i][0] = v[i][0] + v[i][1]
        else:
            continue
    return count


n = 3
v = []
v .append([10, 20])
v .append([15, 10])
v .append([20, 16])
print(find_max(v, n))

# Expected output:
2
# count of substrings formed using a given set of characters only | function to find the number of substrings that can be formed using given characters ; boolean array for storing the available characters ; mark indices of all available characters as 1 ; initialize lastpos as - 1 ; initialize ans with the total no of possible substrings ; traverse the string from left to right ; if the current character is not present in b ; subtract the total possible substrings ; update the value of lastpos to current index ; print the final answer ; given string ; 
def numberofsubstrings(str, k, charArray):
    N = len(str)
    available = [0] * 26
    for i in range(0, k):
        available[ord(charArray[i]) - ord('a')] = 1
    lastPos = -1
    ans = (N * (N + 1)) / 2
    for i in range(0, N):
        if (available[ord(str[i]) - ord('a')] == 0):
            ans -= ((i - lastPos) * (N - i))
            lastPos = i
    print(int(ans))


str = "abcb"
k = 2
charArray = ['a', 'b']
numberofsubstrings(str, k, charArray)

# Expected output:
4
# minimum cost to reach a point n from 0 with two different operations allowed | function to return minimum cost to reach destination ; initialize cost to 0 ; going backwards until we reach initial position ; if 2 * x jump is better than x + 1 ; if x + 1 jump is better ; 
def minCost(N, P, Q):
    cost = 0
    while (N > 0):
        if (N & 1):
            cost += P
            N -= 1
        else:
            temp = N // 2
            if (temp * P > Q):
                cost += Q
            else:
                cost += P * temp
            N //= 2
    return cost


N = 9
P = 5
Q = 1
print(minCost(N, P, Q))

# Expected output:
13
# number of ways to reach at starting node after travelling through exactly k edges in a complete graph | function to find number of ways to reach from node 1 to 1 again , after moving exactly k edges ; initialize a dp [ ] array , where dp [ i ] stores number of ways to reach at a i node ; base case ; iterate for the number of edges moved ; sum will store number of ways to reach all the nodes ; iterate for every possible state for the current step ; update the value of the dp array after travelling each edge ; print dp [ 0 ] as the answer ; 
def numberOfWays(n, k):
    dp = [0 for i in range(1000)]
    dp[0] = 1
    for i in range(1, k + 1, 1):
        numWays = 0
        for j in range(n):
            numWays += dp[j]
        for j in range(n):
            dp[j] = numWays - dp[j]
    print(dp[0])


if __name__ == '__main__':
    N = 5
    K = 3
    numberOfWays(N, K)

# Expected output:
12
# minimum cost of purchasing at least x chocolates | function to calculate minimum cost of buying least x chocolates ; base case ; include the i - th box ; exclude the i - th box ; return the minimum of the above two cases ; 
def findMinCost(arr, X, n, i=0):
    if (X <= 0):
        return 0
    if (i >= n):
        return 10 ** 8
    inc = findMinCost(arr, X - arr[i][0], n, i + 1)
    if (inc != 10 ** 8):
        inc += arr[i][1]
    exc = findMinCost(arr, X, n, i + 1)
    return min(inc, exc)


if __name__ == '__main__':
    arr = [[4, 3], [3, 2], [2, 4], [1, 3], [4, 2]]
    X = 7
    n = len(arr)
    ans = findMinCost(arr, X, n)
    if (ans != 10 ** 8):
        print(ans)
    else:
        print(-1)

# Expected output:
4
# probability that the sum of all numbers obtained on throwing a dice n times lies between two given integers | function to calculate the probability for the given sum to be equal to sum in n throws of dice ; base cases ; 
def find(N, sum):
    if (sum > 6 * N or sum < N):
        return 0
    if (N == 1):
        if (sum >= 1 and sum <= 6):
            return 1.0 / 6
        else:
            return 0
    s = 0
    for i in range(1, 7):
        s = s + find(N - 1, sum - i) / 6
    return s


if __name__ == "__main__":
    N = 4
    a = 13
    b = 17
    probability = 0.0
    for sum in range(a, b + 1):
        probability = probability + find(N, sum)
    print(round(probability, 6))

# Expected output:
0.505401
# minimum steps to reduce n to 0 by given operations | function to find the minimum number to steps to reduce n to 0 ; base case ; recursive call to count the minimum steps needed ; return the answer ; 
def minDays(n):
    if n < 1:
        return n
    cnt = 1 + min(n % 2 + minDays(n // 2), n % 3 + minDays(n // 3))
    return cnt


N = 6
print(str(minDays(N)))

# Expected output:
4