giulio98/xlcost-single-prompt huggingface dataset:
# minimize coins required to obtain all possible values up to n | function to find minimum count of { 1 , 2 , 5 } valued coins required to make a change of all values in the range [ 1 , n ] ; number of 5 valueds coins required ; number of 1 valued coins required ; number of 2 valued coins required ; 
def find(N):
    F = int((N - 4) / 5)
    if ((N - 5 * F) % 2) == 0:
        O = 2
    else:
        O = 1
    T = (N - 5 * F - O) // 2
    print("Count of 5 valueds coins: ", F)
    print("Count of 2 valueds coins: ", T)
    print("Count of 1 valueds coins: ", O)


if __name__ == '__main__':
    N = 8
    find(N)

# Expected output:
Count of 5 valueds coins:  0
Count of 2 valueds coins:  3
Count of 1 valueds coins:  2
# check if given string is a substring of string formed by repeated concatenation of z to a | function checks if a given is valid or not and prints the output ; boolean flag variable to mark if given is valid ; traverse the given string ; if adjacent character differ by 1 ; if character ' a ' is followed by 4 ; else flip the flag and break from the loop ; output according to flag variable ; 
def checkInfinite(s):
    flag = 1
    N = len(s)
    for i in range(N - 1):
        if (s[i] == chr(ord(s[i + 1]) + 1)):
            continue
        elif (s[i] == 'a' and s[i + 1] == 'z'):
            continue
        else:
            flag = 0
            break
    if (flag == 0):
        print("NO")
    else:
        print("YES")


if __name__ == '__main__':
    s = "ecbaz"
    checkInfinite(s)

# Expected output:
NO
# minimum change in lanes required to cross all barriers | function to find the minimum number of changes of lane required ; if there is a barrier , then add very large value ; add the minimum value to move forword with or without crossing barrier ; return the minimum value of dp [ 0 ] , dp [ 1 ] and dp [ 2 ] ; 
def minChangeInLane(barrier, n):
    dp = [1, 0, 1]
    for j in range(n):
        val = barrier[j]
        if (val > 0):
            dp[val - 1] = 1000000
        for i in range(3):
            if (val != i + 1):
                dp[i] = min(dp[i], min(dp[(i + 1) % 3], dp[(i + 2) % 3]) + 1)
    return min(dp[0], min(dp[1], dp[2]))


barrier = [0, 1, 2, 3, 0]
N = len(barrier)
print(minChangeInLane(barrier, N))

# Expected output:
2
# queries to count groups of n students possible having sum of ratings within given range | function to count number of ways to get given sum groups ; initialise dp array ; mark all 1 st row values as 1 since the mat [ 0 ] [ i ] is all possible sums in first row ; fix the ith row ; fix the sum ; iterate through all values of ith row ; if sum can be obtained ; find the prefix sum of last row ; traverse each query ; no of ways to form groups ; 
def numWays(ratings, queries, n, k):
    dp = [[0 for i in range(10002)]for j in range(n)]
    for i in range(k):
        dp[0][ratings[0][i]] += 1
    for i in range(1, n):
        for sum in range(10001):
            for j in range(k):
                if (sum >= ratings[i][j]):
                    dp[i][sum] += dp[i - 1][sum - ratings[i][j]]
    for sum in range(1, 10001):
        dp[n - 1][sum] += dp[n - 1][sum - 1]
    for q in range(len(queries)):
        a = queries[q][0]
        b = queries[q][1]
        print(dp[n - 1][b] - dp[n - 1][a - 1], end=" ")


if __name__ == '__main__':
    N = 2
    K = 3
    ratings = [[1, 2, 3], [4, 5, 6]]
    queries = [[6, 6], [1, 6]]
    numWays(ratings, queries, N, K)

# Expected output:
2 3
# number of permutation with k inversions | set 2 | function to count permutations with k inversions ; store number of permutations with k inversions ; if n = 1 only 1 permutation with no inversion ; for k = 0 only 1 permutation with no inversion ; otherwise update each dp state as per the reccurrance relation formed ; print final count ; 
def numberOfPermWithKInversion(N, K):
    dp = [[0] * (K + 1)] * 2
    mod = 1000000007
    for i in range(1, N + 1):
        for j in range(0, K + 1):
            if (i == 1):
                dp[i % 2][j] = 1 if (j == 0)else 0
            elif (j == 0):
                dp[i % 2][j] = 1
            else:
                var = (0 if (max(j - (i - 1), 0) == 0)
                       else dp[1 - i % 2][max(j - (i - 1), 0) - 1])
                dp[i %
                   2][j] = ((dp[i %
                                2][j - 1] %
                             mod + (dp[1 - i %
                                       2][j] - (var) + mod) %
                             mod) %
                            mod)
    print(dp[N % 2][K])


if __name__ == '__main__':
    N = 3
    K = 2
    numberOfPermWithKInversion(N, K)

# Expected output:
2
# treasure and cities | k is current index and col is previous color . ; base case ; check if color of this city is equal to prev visited city ; return max of both options ; 
def MaxProfit(treasure, color, n, k, col, A, B):
    sum = 0
    if k == n:
        return 0
    if col == color[k]:
        sum += max(A *
                   treasure[k] +
                   MaxProfit(treasure, color, n, k +
                             1, color[k], A, B), MaxProfit(treasure, color, n, k +
                                                           1, col, A, B))
    else:
        sum += max(B *
                   treasure[k] +
                   MaxProfit(treasure, color, n, k +
                             1, color[k], A, B), MaxProfit(treasure, color, n, k +
                                                           1, col, A, B))
    return sum


A = -5
B = 7
treasure = [4, 8, 2, 9]
color = [2, 2, 6, 2]
n = len(color)
print(MaxProfit(treasure, color, n, 0, 0, A, B))

# Expected output:
133
# tetranacci numbers | function to return the n - th tetranacci number ; base cases ; base cases ; base cases ; function to print the nth tetranacci number ; 
def printTetraRec(n):
    if (n == 0):
        return 0
    if (n == 1 or n == 2):
        return 1
    if (n == 3):
        return 2
    else:
        return (
            printTetraRec(
                n -
                1) +
            printTetraRec(
                n -
                2) +
            printTetraRec(
                n -
                3) +
            printTetraRec(
                n -
                4))


def printTetra(n):
    print(printTetraRec(n), end=" ")


n = 10
printTetra(n)

# Expected output:
208
# sum of products of all combination taken ( 1 to n ) at a time | to store sum of every combination ; if we have reached sufficient depth ; find the product of combination ; add the product into sum ; recursion to produce different combination ; function to print sum of products of all combination taken 1 - n at a time ; creating temporary array for storing combination ; call combination with r = i for combination taken i at a time ; displaying sum ; 
def Combination(a, combi, n, r, depth, index):
    global Sum
    if index == r:
        product = 1
        for i in range(r):
            product = product * combi[i]
        Sum += product
        return
    for i in range(depth, n):
        combi[index] = a[i]
        Combination(a, combi, n, r, i + 1, index + 1)


def allCombination(a, n):
    global Sum
    for i in range(1, n + 1):
        combi = [0] * i
        Combination(a, combi, n, i, 0, 0)
        print("f(", i, ") --> ", Sum)
        Sum = 0


Sum = 0
n = 5
a = [0] * n
for i in range(n):
    a[i] = i + 1
allCombination(a, n)

# Expected output:
f( 1 ) -->  15
f( 2 ) -->  85
f( 3 ) -->  225
f( 4 ) -->  274
f( 5 ) -->  120
# dynamic programming | high |  ; returns maximum amount of task that can be done till day n ; an array task_dp that stores the maximum task done ; if n = 0 , no solution exists ; if n = 1 , high effort task on that day will be the solution ; fill the entire array determining which task to choose on day i ; 
def max1(x, y):
    return x if (x > y)else y


def maxTasks(high, low, n):
    task_dp = [0] * (n + 1)
    task_dp[0] = 0
    task_dp[1] = high[0]
    for i in range(2, n + 1):
        task_dp[i] = max(high[i - 1] + task_dp[i - 2],
                         low[i - 1] + task_dp[i - 1])
    return task_dp[n]


n = 5
high = [3, 6, 8, 7, 6]
low = [1, 5, 4, 5, 3]
print(maxTasks(high, low, n))

# Expected output:
20
# partition problem | dp | returns true if arr [ ] can be partitioned in two subsets of equal sum , otherwise false ; calculate sum of all elements ; initialize top row as true ; initialize leftmost column , except part [ 0 ] [ 0 ] , as 0 ; fill the partition table in bottom up manner ; uncomment this part to print table ; 
def findPartition(arr, n):
    sum = 0
    i, j = 0, 0
    for i in range(n):
        sum += arr[i]
    if sum % 2 != 0:
        return false
    part = [[True for i in range(n + 1)]for j in range(sum // 2 + 1)]
    for i in range(0, n + 1):
        part[0][i] = True
    for i in range(1, sum // 2 + 1):
        part[i][0] = False
    for i in range(1, sum // 2 + 1):
        for j in range(1, n + 1):
            part[i][j] = part[i][j - 1]
            if i >= arr[j - 1]:
                part[i][j] = (part[i][j] or part[i - arr[j - 1]][j - 1])
    return part[sum // 2][n]


arr = [3, 1, 1, 2, 2, 1]
n = len(arr)
if findPartition(arr, n):
    print("Can be divided into two", "subsets of equal sum")
else:
    print("Can not be divided into ", "two subsets of equal sum")

# Expected output:
Can be divided into two subsets of equal sum
# minimum number of appends of x or y characters from the end to the front required to obtain given string | function to find the minimum operations required to get the given string after appending m or n characters from the end to the front of the string in each operation ; store the original string ; stores the count of operations ; traverse the string ; cut m letters from end ; add cut m letters to beginning ; update j ; check if strings are the same ; cut n letters from end ; add cut n letters to beginning ; update j ; check if strings are the same ; update the turn ; 
def minimumOperations(orig_str, m, n):
    orig = orig_str
    turn = 1
    j = 1
    for i in orig_str:
        m_cut = orig_str[-m:]
        orig_str = orig_str .replace(' ', '')[:-m]
        orig_str = m_cut + orig_str
        j = j + 1
        if orig != orig_str:
            turn = turn + 1
            n_cut = orig_str[-n:]
            orig_str = orig_str .replace(' ', '')[:-n]
            orig_str = n_cut + orig_str
            j = j + 1
        if orig == orig_str:
            break
        turn = turn + 1
    print(turn)


S = "GeeksforGeeks"
X = 5
Y = 3
minimumOperations(S, X, Y)

# Expected output:
3
# minimum rotations required to get the same string | set | prints occurrences of txt [ ] in pat [ ] ; create lps [ ] that will hold the longest prefix suffix values for pattern ; preprocess the pattern ( calculate lps [ ] array ) ; index for txt [ ] , index for pat [ ] ; mismatch after j matches ; do not match lps [ 0. . lps [ j - 1 ] ] characters , they will match anyway ; fills lps [ ] for given pattern pat [ 0. . m - 1 ] ; length of the previous longest prefix suffix ; lps [ 0 ] is always 0 ; the loop calculates lps [ i ] for i = 1 to m - 1 ; ( pat [ i ] != pat [ _len ] ) ; this is tricky . consider the example . aaacaaaa and i = 7. the idea is similar to search step . ; returns count of rotations to get the same string back ; form a string excluding the first character and concatenating the string at the end ; convert the string to character array ; use the kmp search algorithm to find it in o ( n ) time ; 
def KMPSearch(pat, txt):
    M = len(pat)
    N = len(txt)
    lps = [0] * M
    computeLPSArray(pat, M, lps)
    i = 0
    j = 0
    while i < N:
        if pat[j] == txt[i]:
            j += 1
            i += 1
        if j == M:
            return i - j
            j = lps[j - 1]
        elif i < N and pat[j] != txt[i]:
            if j != 0:
                j = lps[j - 1]
            else:
                i = i + 1


def computeLPSArray(pat, M, lps):
    _len = 0
    lps[0] = 0
    i = 1
    while i < M:
        if pat[i] == pat[_len]:
            _len += 1
            lps[i] = _len
            i += 1
        else:
            if _len != 0:
                _len = lps[_len - 1]
            else:
                lps[i] = 0
                i += 1


def countRotations(s):
    s1 = s[1:len(s)] + s
    pat = s[:]
    text = s1[:]
    return 1 + KMPSearch(pat, text)


s1 = "geeks"
print(countRotations(s1))

# Expected output:
5
# dfa for strings not ending with " the " | this function is for the starting state ( zeroth ) of dfa ; on receiving ' t ' or ' t ' goto first state ( 1 ) ; this function is for the first state of dfa ; on receiving ' t ' or ' t ' goto first state ( 1 ) ; on receiving ' h ' or ' h ' goto second state ( 2 ) ; else goto starting state ( 0 ) ; this function is for the second state of dfa ; on receiving ' e ' or ' e ' goto third state ( 3 ) else goto starting state ( 0 ) ; this function is for the third state of dfa ; on receiving ' t ' or ' t ' goto first state ( 1 ) else goto starting state ( 0 ) ; store length of stringing ; 
def start(c):
    if (c == 't' or c == 'T'):
        dfa = 1


def state1(c):
    if (c == 't' or c == 'T'):
        dfa = 1
    elif (c == 'h' or c == 'H'):
        dfa = 2
    else:
        dfa = 0


def state2(c):
    if (c == 'e' or c == 'E'):
        dfa = 3
    else:
        dfa = 0


def state3(c):
    if (c == 't' or c == 'T'):
        dfa = 1
    else:
        dfa = 0


def isAccepted(string):
    length = len(string)
    for i in range(length):
        if (dfa == 0):
            start(string[i])
        elif (dfa == 1):
            state1(string[i])
        elif (dfa == 2):
            state2(string[i])
        else:
            state3(string[i])
    return (dfa != 3)

if __name__ == "__main__":
    string = "forTHEgeeks"
    dfa = 0
    if isAccepted(string):
        print("ACCEPTED")
    else:
        print("NOT ACCEPTED")

# Expected output:
ACCEPTED
# print characters having prime frequencies in order of occurrence | python 3 implementation of the approach ; function to create sieve to check primes ; false here indicates that it is not prime ; if prime [ p ] is not changed , then it is a prime ; update all multiples of p , set them to non - prime ; function to print the prime frequency characters in the order of their occurrence ; function to create sieve to check primes ; to store the frequency of each of the character of the string ; update the frequency of each character ; traverse str character by character ; if frequency of current character is prime ; 

from math import sqrt
SIZE = 26


def SieveOfEratosthenes(prime, p_size):
    prime[0] = False
    prime[1] = False
    for p in range(2, int(sqrt(p_size)), 1):
        if (prime[p]):
            for i in range(p * 2, p_size, p):
                prime[i] = False


def printChar(str, n):
    prime = [True for i in range(n + 1)]
    SieveOfEratosthenes(prime, len(str) + 1)
    freq = [0 for i in range(SIZE)]
    for i in range(n):
        freq[ord(str[i]) - ord('a')] += 1
    for i in range(n):
        if (prime[freq[ord(str[i]) - ord('a')]]):
            print(str[i], end="")


if __name__ == '__main__':
    str = "geeksforgeeks"
    n = len(str)
    printChar(str, n)

# Expected output:
gksgks
# print characters having prime frequencies in order of occurrence | python code for the above approach ; function to check primes ; counting the frequency of all character using counter function ; traversing string ; 

from collections import Counter
import math


def prime(n):
    if n <= 1:
        return False
    max_div = math .floor(math .sqrt(n))
    for i in range(2, 1 + max_div):
        if n % i == 0:
            return False
    return True


def checkString(s):
    freq = Counter(s)
    for i in range(len(s)):
        if prime(freq[s[i]]):
            print(s[i], end="")


s = "geeksforgeeks"
checkString(s)

# Expected output:
gksgks
# print characters having even frequencies in order of occurrence | python3 implementation of the approach ; function to print the even frequency characters in the order of their occurrence ; to store the frequency of each of the character of the stringing initialize all elements of freq [ ] to 0 ; update the frequency of each character ; traverse string character by character ; if frequency of current character is even ; 

SIZE = 26


def printChar(string, n):
    freq = [0] * SIZE
    for i in range(0, n):
        freq[ord(string[i]) - ord('a')] += 1
    for i in range(0, n):
        if (freq[ord(string[i]) - ord('a')] % 2 == 0):
            print(string[i], end="")


if __name__ == '__main__':
    string = "geeksforgeeks"
    n = len(string)
    printChar(string, n)

# Expected output:
geeksgeeks
# compare two strings considering only alphanumeric characters | function to check alphanumeric equality of both strings ; variable declaration ; length of first string ; length of second string ; to check each and every character of both string ; if the current character of the first string is not an alphanumeric character , increase the pointer i ; if the current character of the second string is not an alphanumeric character , increase the pointer j ; if all alphanumeric characters of both strings are same , then return true ; if any alphanumeric characters of both strings are not same , then return false ; if current character matched , increase both pointers to check the next character ; if not same , then return false ; function to print equal or unequal if strings are same or not ; check alphanumeric equality of both strings ; if both are alphanumeric equal , print equal ; otherwise print unequal ; 
def CompareAlphanumeric(str1, str2):
    i = 0
    j = 0
    len1 = len(str1)
    len2 = len(str2)
    while (i <= len1 and j <= len2):
        while (
            i < len1 and (
                ((str1[i] >= 'a' and str1[i] <= 'z') or (
                    str1[i] >= 'A' and str1[i] <= 'Z') or (
                str1[i] >= '0' and str1[i] <= '9')) == False)):
            i += 1
        while (
            j < len2 and (
                ((str2[j] >= 'a' and str2[j] <= 'z') or (
                    str2[j] >= 'A' and str2[j] <= 'Z') or (
                str2[j] >= '0' and str2[j] <= '9')) == False)):
            j += 1
        if (i == len1 and j == len2):
            return True
        elif (str1[i] != str2[j]):
            return False
        else:
            i += 1
            j += 1
    return False


def CompareAlphanumericUtil(str1, str2):
    res = CompareAlphanumeric(str1, str2)
    if (res):
        print("Equal")
    else:
        print("Unequal")


if __name__ == '__main__':
    str1 = "Ram, Shyam"
    str2 = " Ram - Shyam."
    CompareAlphanumericUtil(str1, str2)
    str1 = "abc123"
    str2 = "123abc"
    CompareAlphanumericUtil(str1, str2)

# Expected output:
Equal
Unequal
# queries to print the character that occurs the maximum number of times in a given range | function that answers all the queries ; length of the string ; number of queries ; prefix array ; iterate for all the characters ; increase the count of the character ; presum array for all 26 characters ; update the prefix array ; answer every query ; range ; iterate for all characters ; times the lowercase character j occurs till r - th index ; subtract the times it occurred till ( l - 1 ) th index ; max times it occurs ; print the answer ; 
def solveQueries(Str, query):
    ll = len(Str)
    Q = len(query)
    pre = [[0 for i in range(256)]for i in range(ll)]
    for i in range(ll):
        pre[i][ord(Str[i])] += 1
        if (i):
            for j in range(256):
                pre[i][j] += pre[i - 1][j]
    for i in range(Q):
        l = query[i][0]
        r = query[i][1]
        maxi = 0
        c = 'a'
        for j in range(256):
            times = pre[r][j]
            if (l):
                times -= pre[l - 1][j]
            if (times > maxi):
                maxi = times
                c = chr(j)
        print("Query ", i + 1, ": ", c)


Str = "striver"
query = [[0, 1], [1, 6], [5, 6]]
solveQueries(Str, query)

# Expected output:
Query  1 :  s
Query  2 :  r
Query  3 :  e
# check whether given string can be generated after concatenating given strings | function that return true if pre is a prefix of str ; while there are characters to match ; if characters differ at any position ; str starts with pre ; function that return true if suff is a suffix of str ; while there are characters to match ; if characters differ at any position ; str ends with suff ; function that returns true if str = a + b or str = b + a ; str cannot be generated by concatenating a and b ; if str starts with a i . e . a is a prefix of str ; check if the rest of the characters are equal to b i . e . b is a suffix of str ; if str starts with b i . e . b is a prefix of str ; check if the rest of the characters are equal to a i . e . a is a suffix of str ; 
def startsWith(str, pre):
    strLen = len(str)
    preLen = len(pre)
    i = 0
    j = 0
    while (i < strLen and j < preLen):
        if (str[i] != pre[j]):
            return False
        i += 1
        j += 1
    return True


def endsWith(str, suff):
    i = len(str) - 1
    j = len(suff) - 1
    while (i >= 0 and j >= 0):
        if (str[i] != suff[j]):
            return False
        i -= 1
        j -= 1
    return True


def checkString(str, a, b):
    if (len(str) != len(a) + len(b)):
        return False
    if (startsWith(str, a)):
        if (endsWith(str, b)):
            return True
    if (startsWith(str, b)):
        if (endsWith(str, a)):
            return True
    return False


str = "GeeksforGeeks"
a = "Geeksfo"
b = "rGeeks"
if (checkString(str, a, b)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# print characters having odd frequencies in order of occurrence | python3 implementation of the approach ; function to print the odd frequency characters in the order of their occurrence ; to store the frequency of each of the character of the string and initialize all elements of freq [ ] to 0 ; update the frequency of each character ; traverse str character by character ; if frequency of current character is odd ; 

import sys
import math


def printChar(str_, n):
    freq = [0] * 26
    for i in range(n):
        freq[ord(str_[i]) - ord('a')] += 1
    for i in range(n):
        if (freq[ord(str_[i]) - ord('a')]) % 2 == 1:
            print("{}".format(str_[i]), end="")


if __name__ == '__main__':
    str_ = "geeksforgeeks"
    n = len(str_)
    printChar(str_, n)

# Expected output:
for
# minimum number of operations to move all uppercase characters before all lower case characters | function to return the minimum number of operations required ; to store the indices of the last uppercase and the first lowercase character ; find the last uppercase character ; find the first lowercase character ; if all the characters are either uppercase or lowercase ; count of uppercase characters that appear after the first lowercase character ; count of lowercase characters that appear before the last uppercase character ; return the minimum operations required ; 
def minOperations(str, n):
    lastUpper = -1
    firstLower = -1
    for i in range(n - 1, -1, -1):
        if (str[i].isupper()):
            lastUpper = i
            break
    for i in range(n):
        if (str[i].islower()):
            firstLower = i
            break
    if (lastUpper == -1 or firstLower == -1):
        return 0
    countUpper = 0
    for i in range(firstLower, n):
        if (str[i].isupper()):
            countUpper += 1
    countLower = 0
    for i in range(lastUpper):
        if (str[i].islower()):
            countLower += 1
    return min(countLower, countUpper)


if __name__ == "__main__":
    str = "geEksFOrGEekS"
    n = len(str)
    print(minOperations(str, n))

# Expected output:
6