giulio98/xlcost-single-prompt huggingface dataset:
# count substrings with different first and last characters | function to count the substrings having different first & last character ; stores frequency of each char ; loop to store frequency of the characters in a map ; to store final result ; traversal of string ; store answer for every iteration ; map traversal ; compare current char ; print the final count ; 
def countSubstring(s, n):
    m = {}
    for i in range(n):
        if s[i] in m:
            m[s[i]] += 1
        else:
            m[s[i]] = 1
    ans = 0
    for i in range(n):
        cnt = 0
        if s[i] in m:
            m[s[i]] -= 1
        else:
            m[s[i]] = -1
        for value in m:
            if (value == s[i]):
                continue
            else:
                cnt += m[value]
        ans += cnt
    print(ans)


S = "abcab"
N = 5
countSubstring(S, N)

# Expected output:
8
# maximize count of empty water bottles from n filled bottles | function to find the maximum bottles that can be emptied ; iterate until a is non - zero ; add the number of bottles that are emptied ; update a after exchanging empty bottles ; stores the number of bottles left after the exchange ; return the answer ; 
def maxBottles(n, e):
    s = 0
    b = 0
    a = n
    while (a != 0):
        s = s + a
        a = (a + b) // e
        b = n - (a * e)
        n = a + b
    return s


if __name__ == '__main__':
    n = 9
    e = 3
    s = maxBottles(n, e)
    print(s)

# Expected output:
13
# count all n digit numbers whose digits are multiple of x | function to calculate x ^ n using binary - exponentiation ; stores the resultant power ; stores the value of x ^ ( n / 2 ) ; function to count an - digit numbers whose digits are multiples of x ; count adigits which are multiples of x ; check if current number is a multiple of x ; increase count of multiples ; check if it 's a 1 digit number ; count the total numbers ; return the total numbers ; 
def power(x, n):
    temp = []
    if (n == 0):
        return 1
    temp = power(x, n // 2)
    if (n % 2 == 0):
        return temp * temp
    else:
        return x * temp * temp


def count_Total_Numbers(n, x):
    total, multiples = 0, 0
    for i in range(10):
        if (i % x == 0):
            multiples += 1
    if (n == 1):
        return multiples
    total = ((multiples - 1) * power(multiples, n - 1))
    return total


if __name__ == '__main__':
    N = 1
    X = 3
    print(count_Total_Numbers(N, X))

# Expected output:
4
# find the vertex diagonally opposite to the vertex m from an n | function to return the required vertex ; case 1 : ; case 2 : ; 
def getPosition(N, M):
    if (M > (N // 2)):
        return (M - (N // 2))
    return (M + (N // 2))


N = 8
M = 5
print(getPosition(N, M))

# Expected output:
1
# maximize count of strings of length 3 that can be formed from n 1 s and m 0 s | function that counts the number of strings of length three that can be made with given m 0 s and n 1 s ; iterate until n & m are positive ; case 1 : ; case 2 : ; print the count of strings ; 
def number_of_strings(N, M):
    ans = 0
    while (N > 0 and M > 0):
        if (N > M):
            if (N >= 2):
                N -= 2
                M -= 1
                ans += 1
            else:
                break
        else:
            if M >= 2:
                M -= 2
                N -= 1
                ans += 1
            else:
                break
    print(ans)


if __name__ == '__main__':
    N = 4
    M = 19
    number_of_strings(N, M)

# Expected output:
4
# minimize array length by repeatedly replacing pairs of unequal adjacent array elements by their sum | function that returns the minimum length of the array after merging unequal adjacent elements ; stores the first element and its frequency ; traverse the array ; if all elements are equal ; no merge - pair operations can be performed ; otherwise ; 
def minLength(A, N):
    elem = A[0]
    count = 1
    for i in range(1, N):
        if (A[i] == elem):
            count += 1
        else:
            break
    if (count == N):
        return N
    else:
        return 1


arr = [2, 1, 3, 1]
N = len(arr)
print(minLength(arr, N))

# Expected output:
1
# reduce n to 0 or less by given x and y operations | function to check if n can be reduced to <= 0 or not ; update n to n / 2 + 10 at most x times ; update n to n - 10 y times ; 
def NegEqu(N, X, Y):
    while (X and N > N // 2 + 10):
        N = N // 2 + 10
        X -= 1
    while (Y):
        N = N - 10
        Y -= 1
    if (N <= 0):
        return True
    return False


if __name__ == '__main__':
    N = 100
    X = 3
    Y = 4
    if (NegEqu(N, X, Y)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# split array into minimum number of subarrays having gcd of its first and last element exceeding 1 | python3 program for the above approach ; function to find the minimum number of subarrays ; right pointer ; left pointer ; count of subarrays ; find gcd ( left , right ) ; found a valid large subarray between arr [ left , right ] ; searched the arr [ 0. . right ] and found no subarray having size > 1 and having gcd ( left , right ) > 1 ; 

from math import gcd


def minSubarrays(arr, n):
    right = n - 1
    left = 0
    subarrays = 0
    while (right >= 0):
        for left in range(right + 1):
            if (gcd(arr[left], arr[right]) > 1):
                subarrays += 1
                right = left - 1
                break
            if (left == right and __gcd(arr[left], arr[right]) == 1):
                return 0
    return subarrays


if __name__ == '__main__':
    N = 6
    arr = [2, 3, 4, 4, 4, 3]
    print(minSubarrays(arr, N))

# Expected output:
2
# find the largest possible value of k such that k modulo x is y | python3 program for the above approach ; function to find the largest positive integer k such that k % x = y ; stores the minimum solution ; return the maximum possible value ; 

import sys


def findMaxSoln(n, x, y):
    ans = -sys .maxsize
    for k in range(n + 1):
        if (k % x == y):
            ans = max(ans, k)
    return (ans if (ans >= 0 and ans <= n)else -1)


if __name__ == '__main__':
    n = 15
    x = 10
    y = 5
    print(findMaxSoln(n, x, y))

# Expected output:
15
# count all numbers up to n having m as the last digit | function to count the numbers ending with m ; stores the count of numbers required ; calculate count upto nearest power of 10 ; computing the value of x ; adding the count of numbers ending at m from x to n ; 
def getCount(N, M):
    total_count = 0
    total_count += N // 10
    x = (N // 10) * 10
    if ((N - x) >= M):
        total_count = total_count + 1
    return total_count


N = 100
M = 1
print(getCount(N, M))

# Expected output:
10
# count of right | python3 program for the above approach ; function to find the number of right angled triangle that are formed from given n points whose perpendicular or base is parallel to x or y axis ; to store the number of points has same x or y coordinates ; store the total count of triangle ; iterate to check for total number of possible triangle ; add the count of triangles formed ; total possible triangle ; 

from collections import defaultdict


def RightAngled(a, n):
    xpoints = defaultdict(lambda: 0)
    ypoints = defaultdict(lambda: 0)
    for i in range(n):
        xpoints[a[i][0]] += 1
        ypoints[a[i][1]] += 1
    count = 0
    for i in range(n):
        if (xpoints[a[i][0]] >= 1 and ypoints[a[i][1]] >= 1):
            count += ((xpoints[a[i][0]] - 1) * (ypoints[a[i][1]] - 1))
    return count


N = 5
arr = [[1, 2], [2, 1], [2, 2], [2, 3], [3, 2]]
print(RightAngled(arr, N))

# Expected output:
4
# smallest subarray which upon repetition gives the original array | function to print the array ; function to find the smallest subarray ; corner case ; initialize the auxiliary subarray ; push the first 2 elements into the subarray brr [ ] ; iterate over the length of subarray ; if array can be divided into subarray of i equal length ; check if on repeating the current subarray gives the original array or not ; subarray found ; add current element into subarray ; no subarray found ; 
def printArray(brr):
    for it in brr:
        print(it, end=' ')


def RepeatingSubarray(arr, N):
    if (N < 2):
        print("-1")
    brr = []
    brr .append(arr[0])
    brr .append(arr[1])
    for i in range(2, N // 2 + 1):
        if (N % i == 0):
            a = False
            n = len(brr)
            j = i
            while (j < N):
                K = j % i
                if (arr[j] == brr[K]):
                    j += 1
                else:
                    a = True
                    break
            if (not a and j == N):
                printArray(brr)
                return
        brr .append(arr[i])
    print("-1")
    return


if __name__ == "__main__":
    arr = [1, 2, 2, 1, 2, 2, 1, 2, 2]
    N = len(arr)
    RepeatingSubarray(arr, N)

# Expected output:
1 2 2
# find all missing numbers from a given sorted array | function to find the missing elements ; initialize diff ; check if diff and arr [ i ] - i both are equal or not ; loop for consecutive missing elements ; 
def printMissingElements(arr, N):
    diff = arr[0]
    for i in range(N):
        if (arr[i] - i != diff):
            while (diff < arr[i] - i):
                print(i + diff, end=" ")
                diff += 1


arr = [6, 7, 10, 11, 13]
N = len(arr)
printMissingElements(arr, N)

# Expected output:
8 9 12
# find all missing numbers from a given sorted array | function to find the missing elements ; initialize an array with zero of size equals to the maximum element in the array ; make b [ i ] = 1 if i is present in the array ; if the element is present make b [ arr [ i ] ] = 1 ; print the indices where b [ i ] = 0 ; 
def printMissingElements(arr, N):
    b = [0] * (arr[N - 1] + 1)
    for i in range(N):
        b[arr[i]] = 1
    for i in range(arr[0], arr[N - 1] + 1):
        if (b[i] == 0):
            print(i, end=" ")


arr = [6, 7, 10, 11, 13]
N = len(arr)
printMissingElements(arr, N)

# Expected output:
8 9 12
# least common element in given two arithmetic sequences | function to find the smallest element common in both the subsequences ; if a is equal to c ; if a exceeds c ; check for the satisfying equation ; least value of possible_y satisfying the given equation will yield true in the below if and break the loop ; if the value of possible_y satisfying the given equation lies in range [ 0 , b ] ; if no value of possible_y satisfies the given equation ; 
def swap(x, y):
    temp = x
    x = y
    y = temp


def smallestCommon(a, b, c, d):
    if (a == c):
        return a
    if (a > c):
        swap(a, c)
        swap(b, d)
    first_term_diff = (c - a)
    possible_y = 0
    for possible_y in range(b):
        if ((first_term_diff % b + possible_y * d) % b == 0):
            break
    if (possible_y != b):
        return c + possible_y * d
    return -1


if __name__ == '__main__':
    A = 2
    B = 20
    C = 19
    D = 9
    print(smallestCommon(A, B, C, D))

# Expected output:
82
# minimum number of flips with rotation to make binary string alternating | function that finds the minimum number of flips to make the binary string alternating if left circular rotation is allowed ; initialize prefix arrays to store number of changes required to put 1 s at either even or odd position ; if i is odd ; update the oddone and evenone count ; else i is even ; update the oddone and evenone count ; initialize minimum flips ; check if substring [ 0 , i ] is appended at end how many changes will be required ; return minimum flips ; given string ; length of 
def MinimumFlips(s, n):
    a = [0] * n
    for i in range(n):
        a[i] = 1 if s[i] == '1'else 0
    oddone = [0] * (n + 1)
    evenone = [0] * (n + 1)
    for i in range(n):
        if (i % 2 != 0):
            if (a[i] == 1):
                oddone[i + 1] = oddone[i] + 1
            else:
                oddone[i + 1] = oddone[i] + 0
            if (a[i] == 0):
                evenone[i + 1] = evenone[i] + 1
            else:
                evenone[i + 1] = evenone[i] + 0
        else:
            if (a[i] == 0):
                oddone[i + 1] = oddone[i] + 1
            else:
                oddone[i + 1] = oddone[i] + 0
            if (a[i] == 1):
                evenone[i + 1] = evenone[i] + 1
            else:
                evenone[i + 1] = evenone[i] + 0
    minimum = min(oddone[n], evenone[n])
    for i in range(n):
        if (n % 2 != 0):
            minimum = min(minimum, oddone[n] - oddone[i + 1] + evenone[i + 1])
            minimum = min(minimum, evenone[n] - evenone[i + 1] + oddone[i + 1])
    return minimum


S = "000001100"
n = len(S)
print(MinimumFlips(S, n))

# Expected output:
3
# create a graph by connecting divisors from n to m and find shortest path | python3 program for the above approach ; function to check the number is prime or not ; base cases ; iterate till [ 5 , sqrt ( n ) ] to detect primarility of numbers ; function to print the shortest path ; use vector to store the factor of m and n ; use map to check if largest common factor previously present or not ; first store m ; check whether m is prime or not ; largest common factor of m ; if m is divisible by i ; store the largest common factor ; for number n ; check whether n is prime ; largest common factor of n ; store the largest common factor ; print the path print factors from m ; to avoid duplicate printing of same element ; print the factors from n ; 

import math


def isprm(n):
    if (n <= 1):
        return 0
    if (n <= 3):
        return 1
    if (n % 2 == 0 or n % 3 == 0):
        return 0
    i = 5
    while i * i <= n:
        if (n % i == 0 or n % (i + 2) == 0):
            return 0
        i += 6
    return 1


def shortestpath(m, n):
    mfactor = []
    nfactor = []
    fre = dict .fromkeys(range(n + 1), 0)
    mfactor .append(m)
    fre[m] = 1
    while (m != 1):
        if (isprm(m)):
            mfactor .append(1)
            fre[1] = 1
            m = 1
        else:
            sqt = (int)(math .sqrt(m))
            for i in range(2, sqt + 1):
                if (m % i == 0):
                    mfactor .append(m // i)
                    fre[m // i] = 1
                    m = (m // i)
                    break
    nfactor .append(n)
    while (fre[n] != 1):
        if (isprm(n)):
            nfactor .append(1)
            n = 1
        else:
            sqt = (int)(math .sqrt(n))
            for i in range(2, sqt + 1):
                if (n % i == 0):
                    nfactor .append(n // i)
                    n = (n // i)
                    break
    for i in range(len(mfactor)):
        if (mfactor[i] == n):
            break
        print(mfactor[i], end=" <--> ")
    for i in range(len(nfactor) - 1, -1, -1):
        if (i == 0):
            print(nfactor[i], end="")
        else:
            print(nfactor[i], end=" <--> ")


if __name__ == "__main__":
    m = 18
    n = 19
    shortestpath(m, n)

# Expected output:
18 <--> 9 <--> 3 <--> 1 <--> 19
# possible number of trees having n vertex | python3 program for the above approach ; function to count the total number of trees possible ; find the max element in the given array ; level array store the number of nodes on level i initially all values are zero ; in this case tree can not be created ; to store the count of trees ; iterate until maxelement ; calculate level [ i ] ^ level [ i + 1 ] ; update the count of tree ; return the final count of trees ; 

mod = int(1e9 + 7)


def NumberOfTrees(arr, N):
    maxElement = max(arr)
    level = [0] * (maxElement + 1)
    for i in range(N):
        level[arr[i]] += 1
    if (arr[0] != 0 or level[0] != 1):
        return 0
    ans = 1
    for i in range(maxElement):
        for j in range(level[i + 1]):
            ans = (ans * level[i]) % mod
    return ans


if __name__ == '__main__':
    N = 7
    arr = [0, 3, 2, 1, 2, 2, 1]
    print(NumberOfTrees(arr, N))

# Expected output:
24
# possible number of trees having n vertex | python3 program for the above approach ; function that finds the value of x ^ y using modular exponentiation ; base case ; if y is odd , multiply x with result ; return the value ; function that counts the total number of trees possible ; find the max element in array ; level array store the number nodes on level i initially all values are 0 ; in this case tree can not be created ; calculate level [ i ] ^ level [ i + 1 ] ; return the final count ; 

mod = int(1e9 + 7)


def power(x, y):
    if (y == 0):
        return 1
    p = power(x, y // 2) % mod
    p = (p * p) % mod
    if (y & 1):
        p = (x * p) % mod
    return p


def NumberOfTrees(arr, N):
    maxElement = max(arr)
    level = [0] * (maxElement + 1)
    for i in range(N):
        level[arr[i]] += 1
    if (arr[0] != 0 or level[0] != 1):
        return 0
    ans = 1
    for i in range(maxElement):
        ans = (ans * power(level[i], level[i + 1])) % mod
    return ans


N = 7
arr = [0, 3, 2, 1, 2, 2, 1]
print(NumberOfTrees(arr, N))

# Expected output:
24
# a binary string game | function to return the result of the game ; length of the string ; list to maintain the lengths of consecutive '1' s in the string ; variable that keeps a track of the current length of the block of consecutive '1' s ; adds non - zero lengths ; this takes care of the case when the last character is '1 ; sorts the lengths in descending order ; scores of the 2 players ; for player 1 ; for player 2 ; in case of a tie ; print the result ; 
def gameMax(S):
    N = len(S)
    list = []
    one = 0
    for i in range(N):
        if (S[i] == '1'):
            one += 1
        else:
            if (one != 0):
                list .append(one)
            one = 0

    if (one != 0):
        list .append(one)
    list .sort(reverse=True)
    score_1 = 0
    score_2 = 0
    for i in range(len(list)):
        if (list[i] % 2 == 1):
            score_1 += list[i]
        else:
            score_2 += list[i]
    if (score_1 == score_2):
        return '-1'
    if (score_1 > score_2):
        return "Player 1"
    else:
        return "Player 2"


S = "11111101"
print(gameMax(S))

# Expected output:
Player 2
# count of carry operations on adding two binary numbers | function to count the number of carry operations to add two binary numbers ; to store the carry count ; iterate till there is no carry ; carry now contains common set bits of x and y ; sum of bits of x and y where at least one of the bits is not set ; carry is shifted by one so that adding it to x gives the required sum ; adding number of 1 's of  carry to final count ; return the final count ; 
def carryCount(num1, num2):
    count = 0
    while (num2 != 0):
        carry = num1 & num2
        num1 = num1 ^ num2
        num2 = carry << 1
        count += bin(num2).count('1')
    return count


A = 15
B = 10
print(carryCount(A, B))

# Expected output:
3
# count of all possible ways to reach a target by a knight | python3 program to implement above approach ; function to return x ^ y % mod ; base case ; function to return the inverse of factorial of n ; base case ; function to return factorial of n % mod ; base case ; function to return the value of n ! / ( ( n - k ) ! * k ! ) ; function to return the count of ways to reach ( n , m ) from ( 0 , 0 ) ; if ( n + m ) % 3 != 0 ; no possible way exists ; calculate x and y from the equations x + 2 y = n and 2 x + y == m ; 

Mod = int(1e9 + 7)


def power(X, Y, Mod):
    if Y == 0:
        return 1
    p = power(X, Y // 2, Mod) % Mod
    p = (p * p) % Mod
    if Y & 1:
        p = (X * p) % Mod
    return p


def Inversefactorial(N):
    if N <= 0:
        return 1
    fact = 1
    for i in range(1, N + 1):
        fact = (fact * i) % Mod
    return power(fact, Mod - 2, Mod)


def factorial(N):
    if N <= 0:
        return 1
    fact = 1
    for i in range(1, N + 1):
        fact = (fact * i) % Mod
    return fact


def nck(N, K):
    factN = factorial(N)
    inv = Inversefactorial(K)
    invFact = Inversefactorial(N - K)
    return (((factN * inv) % Mod) * invFact) % Mod


def TotalWays(N, M):
    if (N + M) % 3 != 0:
        return 0
    X = N - (N + M) // 3
    Y = M - (N + M) // 3
    if X < 0 or Y < 0:
        return 0
    return nck(X + Y, Y)


N, M = 3, 3
print(TotalWays(N, M))

# Expected output:
2
# lead a life problem | function that calculates the profit with the earning and cost of expenses ; to store the total profit ; loop for n number of days ; if last day , no need to buy food ; else buy food to gain energy for next day ; update earning per day ; update profit with daily spent ; print the profit ; 
def calculateProfit(n, earnings, cost, e):
    profit = 0
    for i in range(n):
        earning_per_day = 0
        daily_spent_food = 0
        if (i == (n - 1)):
            earning_per_day = earnings[i] * e
            profit = profit + earning_per_day
            break
        if (cost[i] < earnings[i]):
            earning_per_day = earnings[i] * e
            daily_spent_food = cost[i] * e
            profit = (profit + earning_per_day - daily_spent_food)
    print(profit)


if __name__ == '__main__':
    n = 4
    earnings = [1, 8, 6, 7]
    cost = [1, 3, 4, 1]
    e = 5
    calculateProfit(n, earnings, cost, e)

# Expected output:
70
# check if n numbers with even sum can be selected from a given array | function to check if an odd sum can be made using n integers from the array ; initialize odd and even counts ; iterate over the array to count the no . of even and odd integers ; if element is odd ; if element is even ; check if even_freq is more than n ; if odd_freq is odd ; consider even count of odd ; calculate even required ; if even count is less than required count ; calculate even required ; if even count is less than required count ; 
def checkEvenSum(arr, N, size):
    even_freq, odd_freq = 0, 0
    for i in range(size):
        if (arr[i] & 1):
            odd_freq += 1
        else:
            even_freq += 1
    if (even_freq >= N):
        return True
    else:
        if (odd_freq & 1):
            taken = odd_freq - 1
            req = N - taken
            if (even_freq < req):
                return False
            else:
                return True
        else:
            taken = odd_freq
            req = N - taken
            if (even_freq < req):
                return False
            else:
                return True
    return False


if __name__ == "__main__":
    arr = [9, 2, 3, 4, 18, 7, 7, 6]
    size = len(arr)
    N = 5
    if (checkEvenSum(arr, N, size)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# minimum count of digits required to obtain given sum | function to print the minimum count of digits ; if n is divisible by 9 ; count of 9 's is the answer ; if remainder is non - zero ; 
def mindigits(n):
    if (n % 9 == 0):
        print(n // 9)
    else:
        print((n // 9) + 1)


if __name__ == '__main__':
    n1 = 24
    n2 = 18
    mindigits(n1)
    mindigits(n2)

# Expected output:
3
2
# count of all possible numbers not exceeding m having suffix n | function to count the no . of digits of n ; function to count all possible numbers having suffix as n ; difference of the a . p ; count of the number of terms ; 
def digitsOf(num):
    return len(str(num))


def count(a, tn):
    diff = int(pow(10, digitsOf(a)))
    return ((tn - a) / diff) + 1


if __name__ == '__main__':
    n = 25
    m = 4500
    print(int(count(n, m)))

# Expected output:
45