giulio98/xlcost-single-prompt huggingface dataset:
# find the sum of all betrothed numbers up to n | python3 program to find the sum of the all betrothed numbers up to n ; function to find the sum of the all betrothed numbers ; to store the betrothed numbers ; calculate sum of number_1 's divisors ; i = 2 because we don 't  want to include  1 as a divisor. ; sum all betrothed numbers up to n ; 

import math


def Betrothed_Sum(n):
    Set = []
    for number_1 in range(1, n):
        sum_divisor_1 = 1
        i = 2
        while i * i <= number_1:
            if (number_1 % i == 0):
                sum_divisor_1 = sum_divisor_1 + i
                if (i * i != number_1):
                    sum_divisor_1 += number_1 // i
            i = i + 1
        if (sum_divisor_1 > number_1):
            number_2 = sum_divisor_1 - 1
            sum_divisor_2 = 1
            j = 2
            while j * j <= number_2:
                if (number_2 % j == 0):
                    sum_divisor_2 += j
                    if (j * j != number_2):
                        sum_divisor_2 += number_2 // j
                j = j + 1
            if (sum_divisor_2 == number_1 +
                    1 and number_1 <= n and number_2 <= n):
                Set .append(number_1)
                Set .append(number_2)
    Summ = 0
    for i in Set:
        if i <= n:
            Summ += i
    return Summ


n = 78
print(Betrothed_Sum(n))

# Expected output:
123
# probability of rain on n + 1 th day | function to find the probability ; count occurence of 1 ; find probability ; 
def rainDayProbability(a, n):
    count = a .count(1)
    m = count / n
    return m


if __name__ == "__main__":
    a = [1, 0, 1, 0, 1, 1, 1, 1]
    n = len(a)
    print(rainDayProbability(a, n))

# Expected output:
0.75
# program to find the sum of a series 1 + 1 / 2 ^ 2 + 1 / 3 ^ 3 + â €¦ . . + 1 / n ^ n | function to calculate the following series ; 
def Series(n):
    sums = 0.0
    for i in range(1, n + 1):
        ser = 1 / (i ** i)
        sums += ser
    return sums


n = 3
res = round(Series(n), 5)
print(res)

# Expected output:
1.28704
# lexicographically largest string formed in minimum moves by replacing characters of given string | function to print the lexicographically the largest string obtained in process of obtaining a string containing first n lower case english alphabtes ; store the frequency of each character ; traverse the string s ; stores the characters which are not appearing in s ; stores the index of the largest character in the array v , that need to be replaced ; traverse the string , s ; if frequency of s [ i ] is greater than 1 or it is outside the range ; decrement its frequency by 1 ; update s [ i ] ; decrement j by 1 ; traverse the string , s ; decrement its frequency by 1 ; update s [ i ] ; increment l by 1 ; return s ; 
def lexicographicallyMaximum(S, N):
    M = {}
    for i in range(N):
        if S[i] in M:
            M[S[i]] += 1
        else:
            M[S[i]] = 1
    V = []
    for i in range(ord('a'), ord('a') + min(N, 25)):
        if i not in M:
            V .append(chr(i))
    j = len(V) - 1
    for i in range(N):
        if (ord(S[i]) >= (ord('a') + min(N, 25))
                or (S[i] in M and M[S[i]] > 1)):
            if (ord(V[j]) < ord(S[i])):
                continue
            M[S[i]] -= 1
            S = S[0:i] + V[j] + S[(i + 1):]
            j -= 1
        if (j < 0):
            break
    l = 0
    for i in range(N - 1, -1, -1):
        if (l > j):
            break
        if (ord(S[i]) >= (ord('a') + min(N, 25)) or S[i] in M and M[S[i]] > 1):
            M[S[i]] -= 1
            S = S[0:i] + V[l] + S[(i + 1):]
            l += 1
    s = list(S)
    s[len(s) - 1] = 'd'
    S = "".join(s)
    return S


S = "abccefghh"
N = len(S)
print(lexicographicallyMaximum(S, N))

# Expected output:
abicefghd
# check if any subarray can be made palindromic by replacing less than half of its elements | a utility function to check if a subarray can be palindromic by replacing less than half of the elements present in it ; stores frequency of array elements ; traverse the array ; update frequency of each array element ; iterator over the map ; if frequency of any element exceeds 1 ; if no repetition is found ; function to check and print if any subarray can be made palindromic by replacing less than half of its elements ; 
def isConsistingSubarrayUtil(arr, n):
    mp = {}
    for i in range(n):
        if arr[i] in mp:
            mp[arr[i]] += 1
        else:
            mp[arr[i]] = 1
    for it in mp:
        if (mp[it] > 1):
            return True
    return False


def isConsistingSubarray(arr, N):
    if (isConsistingSubarrayUtil(arr, N)):
        print("Yes")
    else:
        print("No")


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

# Expected output:
Yes
# count composite fibonacci numbers from given array | python3 program to implement the above approach ; function to find all fibonacci numbers up to max ; store all fibonacci numbers upto max ; stores previous element of fibonacci sequence ; stores previous element of fibonacci sequence ; insert prev into hashmap ; insert all the fibonacci numbers up to max ; insert curr into hashmap ; stores curr into temp ; update curr ; update prev ; function to find all composite numbers up to max ; isprime [ i ] : stores if i is a prime number or not ; calculate all prime numbers up to max using sieve of eratosthenes ; if p is a prime number ; set all multiple of p as non - prime ; function to find the numbers which is both a composite and fibonacci number ; stores the largest element of the array ; traverse the array arr [ ] ; update max ; isprim [ i ] check i is a prime number or not ; stores all the fibonacci numbers ; traverse the array arr [ ] ; current element is not a composite number ; if current element is a fibonacci and composite number ; print current element ; 

import math


def createhashmap(Max):
    hashmap = {""}
    curr = 1
    prev = 0
    hashmap .add(prev)
    while (curr <= Max):
        hashmap .add(curr)
        temp = curr
        curr = curr + prev
        prev = temp
    return hashmap


def SieveOfEratosthenes(Max):
    isPrime = [1 for x in range(Max + 1)]
    isPrime[0] = 0
    isPrime[1] = 0
    for p in range(0, int(math .sqrt(Max))):
        if (isPrime[p]):
            for i in range(2 * p, Max, p):
                isPrime[i] = 0
    return isPrime


def cntFibonacciPrime(arr, N):
    Max = arr[0]
    for i in range(0, N):
        Max = max(Max, arr[i])
    isPrime = SieveOfEratosthenes(Max)
    hashmap = createhashmap(Max)
    for i in range(0, N):
        if arr[i] == 1:
            continue
        if ((arr[i] in hashmap) and (not (isPrime[arr[i]]))):
            print(arr[i], end=" ")


arr = [13, 55, 7, 3, 5, 21, 233, 144, 89]
N = len(arr)
cntFibonacciPrime(arr, N)

# Expected output:
55 21 144
# reduce a given number to form a key by the given operations | python3 program of the above approach ; function to find the key of the 

import math


def key(N):
    num = "" + str(N)
    ans = 0
    j = 0
    while j < len(num):
        if ((ord(num[j]) - 48) % 2 == 0):
            add = 0
            i = j
            while j < len(num):
                add += ord(num[j]) - 48
                if (add % 2 == 1):
                    break
                j += 1
            if (add == 0):
                ans *= 10
            else:
                digit = int(math .floor(math .log10(add) + 1))
                ans *= (pow(10, digit))
                ans += add
            i = j
        else:
            add = 0
            i = j
            while j < len(num):
                add += ord(num[j]) - 48
                if (add % 2 == 0):
                    break
                j += 1
            if (add == 0):
                ans *= 10
            else:
                digit = int(math .floor(math .log10(add) + 1))
                ans *= (pow(10, digit))
                ans += add
            i = j
        j += 1
    if (j + 1) >= len(num):
        return ans
    else:
        ans += ord(num[len(num) - 1]) - 48
        return ans


N = 1667848271
print(key(N))

# Expected output:
20291
# sentinel linear search | python3 implementation of the approach function to search key in the given array ; function to search x in the given array ; last element of the array ; element to be searched is placed at the last index ; put the last element back ; 
def sentinelSearch(arr, n, key):
    last = arr[n - 1]
    arr[n - 1] = key
    i = 0
    while (arr[i] != key):
        i += 1
    arr[n - 1] = last
    if ((i < n - 1) or (arr[n - 1] == key)):
        print(key, "is present at index", i)
    else:
        print("Element Not found")


arr = [10, 20, 180, 30, 60, 50, 110, 100, 70]
n = len(arr)
key = 180
sentinelSearch(arr, n, key)

# Expected output:
180 is present at index 2
# maximum possible middle element of the array after deleting exactly k elements | function to calculate maximum possible middle value of the array after deleting exactly k elements ; initialize answer as - 1 ; calculate range of elements that can give maximum possible middle value of the array since index of maximum possible middle value after deleting exactly k elements from array will lie in between low and high ; find maximum element of the array in range low and high ; since indexing is 1 based so check element at index i - 1 ; return the maximum possible middle value of the array after deleting exactly k elements from the array ; 
def maximum_middle_value(n, k, arr):
    ans = -1
    low = (n + 1 - k) // 2
    high = (n + 1 - k) // 2 + k
    for i in range(low, high + 1):
        ans = max(ans, arr[i - 1])
    return ans


if __name__ == "__main__":
    n, k = 5, 2
    arr = [9, 5, 3, 7, 10]
    print(maximum_middle_value(n, k, arr))
    n, k = 9, 3
    arr1 = [2, 4, 3, 9, 5, 8, 7, 6, 10]
    print(maximum_middle_value(n, k, arr1))

# Expected output:
7
9
# ternary search | python3 program to illustrate recursive approach to ternary search ; function to perform ternary search ; find the mid1 and mid2 ; check if key is present at any mid ; since key is not present at mid , check in which region it is present then repeat the search operation in that region ; the key lies in between l and mid1 ; the key lies in between mid2 and r ; the key lies in between mid1 and mid2 ; key not found ; 

import math as mt


def ternarySearch(l, r, key, ar):
    if (r >= l):
        mid1 = l + (r - l) // 3
        mid2 = r - (r - l) // 3
        if (ar[mid1] == key):
            return mid1
        if (ar[mid2] == key):
            return mid2
        if (key < ar[mid1]):
            return ternarySearch(l, mid1 - 1, key, ar)
        elif (key > ar[mid2]):
            return ternarySearch(mid2 + 1, r, key, ar)
        else:
            return ternarySearch(mid1 + 1, mid2 - 1, key, ar)
    return -1


l, r, p = 0, 9, 5
ar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
l = 0
r = 9
key = 5
p = ternarySearch(l, r, key, ar)
print("Index of", key, "is", p)
key = 50
p = ternarySearch(l, r, key, ar)
print("Index of", key, "is", p)

# Expected output:
Index of 5 is 4
Index of 50 is -1
# minimum number of points to be removed to get remaining points on one side of axis | function to find the minimum number of points ; number of points on the left of y - axis . ; number of points on the right of y - axis . ; number of points above x - axis . ; number of points below x - axis . ; 
def findmin(p, n):
    a, b, c, d = 0, 0, 0, 0
    for i in range(n):
        if (p[i][0] <= 0):
            a += 1
        elif (p[i][0] >= 0):
            b += 1
        if (p[i][1] >= 0):
            c += 1
        elif (p[i][1] <= 0):
            d += 1
    return min([a, b, c, d])


p = [[1, 1], [2, 2], [-1, -1], [-2, 2]]
n = len(p)
print(findmin(p, n))

# Expected output:
1
# maximum number of pair reductions possible on a given triplet | function to count the maximum number of pair reductions possible on a given triplet ; convert them into an array ; stores count of operations ; sort the array ; if the first two array elements reduce to 0 ; apply the operations ; increment count ; print the maximum count ; 
def maxOps(a, b, c):
    arr = [a, b, c]
    count = 0
    while True:
        arr .sort()
        if not arr[0] and not arr[1]:
            break
        arr[1] -= 1
        arr[2] -= 1
        count += 1
    print(count)


a, b, c = 4, 3, 2
maxOps(a, b, c)

# Expected output:
4
# case | python3 implementation of the approach ; function to return the sorted string ; to store the frequencies of the lowercase and the uppercase characters in the given string ; if current character is lowercase then increment its frequency in the lower [ ] array ; else increment in the upper [ ] array ; pointers that point to the smallest lowercase and the smallest uppercase characters respectively in the given string ; for every character in the given string ; if the current character is lowercase then replace it with the smallest lowercase character available ; decrement the frequency of the used character ; else replace it with the smallest uppercase character available ; decrement the frequency of the used character ; return the sorted string ; 

MAX = 26


def getSortedString(s, n):
    lower = [0] * MAX
    upper = [0] * MAX
    for i in range(n):
        if (s[i].islower()):
            lower[ord(s[i]) - ord('a')] += 1
        elif (s[i].isupper()):
            upper[ord(s[i]) - ord('A')] += 1
    i = 0
    j = 0
    while (i < MAX and lower[i] == 0):
        i += 1
    while (j < MAX and upper[j] == 0):
        j += 1
    for k in range(n):
        if (s[k].islower()):
            while (lower[i] == 0):
                i += 1
            s[k] = chr(i + ord('a'))
            lower[i] -= 1
        elif (s[k].isupper()):
            while (upper[j] == 0):
                j += 1
            s[k] = chr(j + ord('A'))
            upper[j] -= 1
    return "".join(s)


if __name__ == "__main__":
    s = "gEeksfOrgEEkS"
    n = len(s)
    print(getSortedString(list(s), n))

# Expected output:
eEfggkEkrEOsS
# print characters and their frequencies in order of occurrence | python3 implementation to pr the character and its frequency in order of its occurrence ; function to print the character and its frequency in order of its occurrence ; size of the 'str ; initialize all elements of freq [ ] to 0 ; accumulate frequency of each character in 'str ; traverse ' str ' from left to right ; if frequency of character str [ i ] is not equal to 0 ; print the character along with its frequency ; update frequency of str [ i ] to 0 so that the same character is not printed again ; 

import numpy as np


def prCharWithFreq(str):
    n = len(str)
    freq = np.zeros(26, int)
    for i in range(0, n):
        freq[ord(str[i]) - ord('a')] += 1
    for i in range(0, n):
        if (freq[ord(str[i]) - ord('a')] != 0):
            print(str[i], freq[ord(str[i]) - ord('a')],
                  end=" ")
            freq[ord(str[i]) - ord('a')] = 0


if __name__ == "__main__":

    str = "geeksforgeeks"
    prCharWithFreq(str)

# Expected output:
g 2 e 4 k 2 s 2 f 1 o 1 r 1
# segregate prime and non | function to generate prime numbers using sieve of eratosthenes ; if prime [ p ] is unchanged , then it is a prime ; update all multiples of p ; function to segregate the primes and non - primes ; generate all primes till 10 ^ 7 ; initialize left and right ; traverse the array ; increment left while array element at left is prime ; decrement right while array element at right is non - prime ; if left < right , then swap arr [ left ] and arr [ right ] ; swap arr [ left ] and arr [ right ] ; print segregated array ; 
def SieveOfEratosthenes(prime, n):
    p = 2
    while (p * p <= n):
        if (prime[p]):
            i = p * p
            while (i <= n):
                prime[i] = False
                i += p
        p += 1


def segregatePrimeNonPrime(prime, arr, N):
    SieveOfEratosthenes(prime, 10000000)
    left, right = 0, N - 1
    while (left < right):
        while (prime[arr[left]]):
            left += 1
        while (not prime[arr[right]]):
            right -= 1
        if (left < right):
            arr[left], arr[right] = arr[right], arr[left]
            left += 1
            right -= 1
    for num in arr:
        print(num, end=" ")


arr = [2, 3, 4, 6, 7, 8, 9, 10]
N = len(arr)
prime = [True] * 10000001
segregatePrimeNonPrime(prime, arr, N)

# Expected output:
2 3 7 6 4 8 9 10
# calculate depth of a full binary tree from preorder | function to return max of left subtree height or right subtree height ; calc height of left subtree ( in preorder left subtree is processed before right ) ; calc height of right subtree ; wrapper over finddepthrec ( ) ; 
def findDepthRec(tree, n, index):
    if (index[0] >= n or tree[index[0]] == 'l'):
        return 0
    index[0] += 1
    left = findDepthRec(tree, n, index)
    index[0] += 1
    right = findDepthRec(tree, n, index)
    return (max(left, right) + 1)


def findDepth(tree, n):
    index = [0]
    return findDepthRec(tree, n, index)


if __name__ == '__main__':
    tree = "nlnnlll"
    n = len(tree)
    print(findDepth(tree, n))

# Expected output:
3
# check horizontal and vertical symmetry in binary matrix | python3 program to find if a matrix is symmetric . ; initializing as both horizontal and vertical symmetric . ; checking for horizontal symmetry . we compare first row with last row , second row with second last row and so on . ; checking each cell of a column . ; check if every cell is identical ; checking for vertical symmetry . we compare first column with last column , second xolumn with second last column and so on . ; checking each cell of a row . ; check if every cell is identical ; 

MAX = 1000


def checkHV(arr, N, M):
    horizontal = True
    vertical = True
    i = 0
    k = N - 1
    while (i < N // 2):
        for j in range(M):
            if (arr[i][j] != arr[k][j]):
                horizontal = False
                break
        i += 1
        k -= 1
    i = 0
    k = M - 1
    while (i < M // 2):
        for j in range(N):
            if (arr[i][j] != arr[k][j]):
                vertical = False
                break
        i += 1
        k -= 1
    if (not horizontal and not vertical):
        print("NO")
    elif (horizontal and not vertical):
        print("HORIZONTAL")
    elif (vertical and not horizontal):
        print("VERTICAL")
    else:
        print("BOTH")


mat = [[1, 0, 1], [0, 0, 0], [1, 0, 1]]
checkHV(mat, 3, 3)

# Expected output:
BOTH
# replace every matrix element with maximum of gcd of row or column | python3 program to replace each each element with maximum of gcd of row or column . ; returning the greatest common divisor of two number ; finding gcd of each row and column and replacing with each element with maximum of gcd of row or column . ; calculating gcd of each row and each column in o ( mn ) and store in arrays . ; replacing matrix element ; 

R = 3
C = 4


def gcd(a, b):
    if (b == 0):
        return a
    return gcd(b, a % b)


def replacematrix(mat, n, m):
    rgcd = [0] * R
    cgcd = [0] * C
    for i in range(n):
        for j in range(m):
            rgcd[i] = gcd(rgcd[i], mat[i][j])
            cgcd[j] = gcd(cgcd[j], mat[i][j])
    for i in range(n):
        for j in range(m):
            mat[i][j] = max(rgcd[i], cgcd[j])


if __name__ == "__main__":
    m = [[1, 2, 3, 3], [4, 5, 6, 6], [7, 8, 9, 9]]
    replacematrix(m, R, C)
    for i in range(R):
        for j in range(C):
            print(m[i][j], end=" ")
        print()

# Expected output:
1 1 3 3 
1 1 3 3 
1 1 3 3
# program for addition of two matrices | python3 program for addition of two matrices ; this function adds a [ ] [ ] and b [ ] [ ] , and stores the result in c [ ] [ ] ; 

N = 4


def add(A, B, C):
    for i in range(N):
        for j in range(N):
            C[i][j] = A[i][j] + B[i][j]


A = [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]
B = [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]
C = A[:][:]
add(A, B, C)
print("Result matrix is")
for i in range(N):
    for j in range(N):
        print(C[i][j], " ", end='')
    print()

# Expected output:
Result matrix is
2  2  2  2  
4  4  4  4  
6  6  6  6  
8  8  8  8
# program for subtraction of matrices | python 3 program for subtraction of matrices ; this function returns 1 if a [ ] [ ] and b [ ] [ ] are identical otherwise returns 0 ; 

N = 4


def subtract(A, B, C):
    for i in range(N):
        for j in range(N):
            C[i][j] = A[i][j] - B[i][j]


A = [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]
B = [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]
C = A[:][:]
subtract(A, B, C)
print("Result matrix is")
for i in range(N):
    for j in range(N):
        print(C[i][j], " ", end='')
    print()

# Expected output:
Result matrix is
0  0  0  0  
0  0  0  0  
0  0  0  0  
0  0  0  0
# find a fixed point ( value equal to index ) in a given array | python program to check fixed point in an array using linear search ; if no fixed point present then return - 1 ; 
def linearSearch(arr, n):
    for i in range(n):
        if arr[i] is i:
            return i
    return -1


arr = [-10, -1, 0, 3, 10, 11, 30, 50, 100]
n = len(arr)
print("Fixed Point is " + str(linearSearch(arr, n)))

# Expected output:
Fixed Point is 3
# find a fixed point ( value equal to index ) in a given array | python program to check fixed point in an array using binary search ;  ; return - 1 if there is no fixed point ; 
def binarySearch(arr, low, high):
    if high >= low:
        mid = (low + high) // 2
    if mid is arr[mid]:
        return mid
    if mid > arr[mid]:
        return binarySearch(arr, (mid + 1), high)
    else:
        return binarySearch(arr, low, (mid - 1))
    return -1


arr = [-10, -1, 0, 3, 10, 11, 30, 50, 100]
n = len(arr)
print("Fixed Point is " + str(binarySearch(arr, 0, n - 1)))

# Expected output:
Fixed Point is 3
# maximum triplet sum in array | python 3 code to find maximum triplet sum ; initialize sum with int_min ; 
def maxTripletSum(arr, n):
    sm = -1000000
    for i in range(0, n):
        for j in range(i + 1, n):
            for k in range(j + 1, n):
                if (sm < (arr[i] + arr[j] + arr[k])):
                    sm = arr[i] + arr[j] + arr[k]
    return sm


arr = [1, 0, 8, 6, 4, 2]
n = len(arr)
print(maxTripletSum(arr, n))

# Expected output:
18
# maximum triplet sum in array | this function assumes that there are at least three elements in arr [ ] . ; sort the given array ; after sorting the array . add last three element of the given array ; 
def maxTripletSum(arr, n):
    arr .sort()
    return (arr[n - 1] + arr[n - 2] + arr[n - 3])


arr = [1, 0, 8, 6, 4, 2]
n = len(arr)
print(maxTripletSum(arr, n))

# Expected output:
18
# maximum triplet sum in array | this function assumes that there are at least three elements in arr [ ] . ; initialize maximum , second maximum and third maximum element ; update maximum , second maximum and third maximum element ; update second maximum and third maximum element ; update third maximum element ; 
def maxTripletSum(arr, n):
    maxA = -100000000
    maxB = -100000000
    maxC = -100000000
    for i in range(0, n):
        if (arr[i] > maxA):
            maxC = maxB
            maxB = maxA
            maxA = arr[i]
        elif (arr[i] > maxB):
            maxC = maxB
            maxB = arr[i]
        elif (arr[i] > maxC):
            maxC = arr[i]
    return (maxA + maxB + maxC)


arr = [1, 0, 8, 6, 4, 2]
n = len(arr)
print(maxTripletSum(arr, n))

# Expected output:
18
# linear search | python3 code to linearly search x in arr [ ] . if x is present then return its location , otherwise return - 1 ; 
def search(arr, n, x):
    for i in range(0, n):
        if (arr[i] == x):
            return i
    return -1


arr = [2, 3, 4, 10, 40]
x = 10
n = len(arr)
result = search(arr, n, 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