giulio98/xlcost-single-prompt huggingface dataset:
# check if a string can be split into substrings starting with n followed by n characters | function to check if the given can be split into desired substrings ; length of the string ; traverse the string ; extract the digit ; check if the extracted number does not exceed the remaining length ; check for the remaining string ; if generating desired substrings is not possible ; 
def helper(s, pos):
    size = len(s)
    if (pos >= size):
        return True
    if (s[pos].isdigit() == False):
        return False
    num = 0
    for i in range(pos, size):
        num = num * 10 + ord(s[pos]) - 48
        if (i + 1 + num > size):
            return False
        if (helper(s, i + 1 + num)):
            return True
    return False


s = "123abc4db1c"
if (helper(s, 0)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# represent k as sum of n | array to store the n - bonacci series ; function to express k as sum of several n_bonacci numbers ; 

N_bonacci = [0] * 100


def N_bonacci_nums(n, k):
    N_bonacci[0] = 1
    for i in range(1, 51):
        j = i - 1
        while j >= i - k and j >= 0:
            N_bonacci[i] += N_bonacci[j]
            j -= 1
    ans = []
    for i in range(50, -1, -1):
        if (n - N_bonacci[i] >= 0):
            ans .append(N_bonacci[i])
            n -= N_bonacci[i]
    if (len(ans) == 1):
        ans .append(0)
    print(len(ans))
    for i in ans:
        print(i, end=", ")


if __name__ == '__main__':
    n = 21
    k = 5
    N_bonacci_nums(n, k)

# Expected output:
3
16, 4, 1,
# divide n into k parts in the form ( x , 2 x , ... , kx ) for some value of x | function to find the division ; calculating value of x1 ; print - 1 if division is not possible ; get the first number ie x1 then successively multiply it by x1 k times by index number to get the required answer ; 
def solve(n, k):
    d = k * (k + 1)
    if ((2 * n) % d != 0):
        print("-1")
        return
    x1 = 2 * n // d
    for i in range(1, k + 1):
        print(x1 * i, end=" ")


n = 10
k = 4
solve(n, k)

# Expected output:
1 2 3 4
# bitonic string | function to check if the given string is bitonic ; check for increasing sequence ; if end of string has been reached ; check for decreasing sequence ; if the end of string hasn 't  been reached ; return true if bitonic ; 
def checkBitonic(s):
    i = 0
    j = 0
    for i in range(1, len(s)):
        if (s[i] > s[i - 1]):
            continue
        if (s[i] <= s[i - 1]):
            break
    if (i == (len(s) - 1)):
        return True
    for j in range(i + 1, len(s)):
        if (s[j] < s[j - 1]):
            continue
        if (s[j] >= s[j - 1]):
            break
    i = j
    if (i != len(s) - 1):
        return False
    return True


s = "abcdfgcba"
if (checkBitonic(s)):
    print("YES")
else:
    print("NO")

# Expected output:
YES
# find pair with maximum gcd for integers in range 2 to n | function to find the required pair whose gcd is maximum ; if n is even ; if n is odd ; 
def solve(N):
    if (N % 2 == 0):
        print(N // 2, N)
    else:
        print((N - 1) // 2, (N - 1))


N = 10
solve(N)

# Expected output:
5 10
# find initial sequence that produces a given array by cyclic increments upto index p | function to generate and return the required initial arrangement ; store the minimum element in the array ; store the number of increments ; subtract mi - 1 from every index ; start from the last index which had been incremented ; stores the index chosen to distribute its element ; traverse the array cyclically and find the index whose element was distributed ; if any index has its value reduced to 0 ; index whose element was distributed ; store the number of increments at the starting index ; print the original array ; 
def findArray(a, n, P):
    mi = min(a)
    ctr = 0
    mi = max(0, mi - 1)
    for i in range(n):
        a[i] -= mi
        ctr += mi
    i = P - 1
    start = -1
    while (1):
        if (a[i] == 0):
            start = i
            break
        a[i] -= 1
        ctr += 1
        i = (i - 1 + n) % n
    a[start] = ctr
    print(*a, sep=', ')


if __name__ == '__main__':
    N = 5
    P = 2
    arr = [3, 2, 0, 2, 7]
    findArray(arr, N, P)

# Expected output:
2, 1, 4, 1, 6
# generate a unique array of length n with sum of all subarrays divisible by n | function to print the required array ; print array ; 
def makeArray(n):
    for i in range(n):
        print((i + 1) * n, end=" ")


n = 6
makeArray(n)

# Expected output:
6 12 18 24 30 36
# find elements in a given range having at least one odd divisor | function to prints all numbers with at least one odd divisor ; check if the number is not a power of two ; 
def printOddFactorNumber(n, m):
    for i in range(n, m + 1):
        if ((i > 0) and ((i & (i - 1)) != 0)):
            print(i, end=" ")


N = 2
M = 10
printOddFactorNumber(N, M)

# Expected output:
3 5 6 7 9 10
# print the first n terms of the series 6 , 28 , 66 , 120 , 190 , 276 , ... | function to print the series ; initialise the value of k with 2 ; iterate from 1 to n ; print each number ; increment the value of k by 2 for next number ; 
def PrintSeries(n):
    k = 2
    for i in range(0, n):
        print(k * (2 * k - 1), end=' ')
        k = k + 2


n = 12
PrintSeries(n)

# Expected output:
6 28 66 120 190 276 378 496 630 780 946 1128
# find a string which matches all the patterns in the given array | function to find a common string which matches all the pattern ; for storing prefix till first most * without conflicts ; for storing suffix till last most * without conflicts ; for storing all middle characters between first and last * ; loop to iterate over every pattern of the array ; index of the first " * " ; index of last " * " ; iterate over the first " * " ; prefix till first most * without conflicts ; iterate till last most * from last ; make suffix till last most * without conflicts ; take all middle characters in between first and last most * ; 
def find(S, N):
    pref = ""
    suff = ""
    mid = ""

    for i in range(N):
        first = int(S[i].index("*"))
        last = int(S[i].rindex("*"))
        for z in range(len(pref)):
            if (z < first):
                if (pref[z] != S[i][z]):
                    return "*"
        for z in range(len(pref), first):
            pref += S[i][z]
        for z in range(len(suff)):
            if (len(S[i]) - 1 - z > last):
                if (suff[z] != S[i][len(S[i]) - 1 - z]):
                    return "*"
        for z in range(len(suff),
                       len(S[i]) - 1 - last):
            suff += S[i][len(S[i]) - 1 - z]
        for z in range(first, last + 1):
            if (S[i][z] != '*'):
                mid += S[i][z]

    suff = suff[:: -1]
    return pref + mid + suff


N = 3
s = ["" for i in range(N)]
s[0] = "pq*du*q"
s[1] = "pq*abc*q"
s[2] = "p*d*q"
print(find(s, N))

# Expected output:
pqduabcdq
# mountain sequence pattern | python3 program for the above approach ; function to print pattern recursively ; base case ; condition to check row limit ; condition for assigning gaps ; conditions to print * ; else print '  ; recursive call for columns ; recursive call for rows ; 

k1 = 2
k2 = 2
gap = 5


def printPattern(i, j, n):
    global k1
    global k2
    global gap
    if (j >= n):
        k1 = 2
        k2 = 2
        k1 -= 1
        k2 += 1
        if (i == 2):
            k1 = 0
            k2 = n - 1
        return 0
    if (i >= 3):
        return 1
    if (j > k2):
        k1 += gap
        k2 += gap
    if (j >= k1 and j <= k2 or i == 2):
        print("*", end="")
    else:
        print(" ", end="")
    if (printPattern(i, j + 1, n) == 1):
        return 1
    print()
    return (printPattern(i + 1, 0, n))


N = 3
printPattern(0, 0, N * 5)

# Expected output:
  *    *    *  
 ***  ***  *** 
***************
# build a dfa to accept binary strings that starts or ends with "01" | function for transition state a ; state transition to b if the character is 0 ; state transition to d if the character is 1 ; function for transition state b ; check if the string has ended ; state transition to c if the character is 1 ; state transition to d if the character is 0 ; function for transition state c ; function for transition state d ; state transition to d if the character is 1 ; state transition to e if the character is 0 ; function for transition state e ; state transition to e if the character is 0 ; state transition to f if the character is 1 ; function for transition state f ; state transition to d if the character is 1 ; state transition to e if the character is 0 ; 
def stateB(n):
    if (len(n) == 0):
        print("string not accepted")
    else:
        if (n[0] == '1'):
            stateC(n[1:])
        else:
            stateD(n[1:])


def stateC(n):
    print("String accepted")


def stateD(n):
    if (len(n) == 0):
        print("string not accepted")
    else:
        if (n[0] == '1'):
            stateD(n[1:])
        else:
            stateE(n[1:])


def stateE(n):
    if (len(n) == 0):
        print("string not accepted")
    else:
        if (n[0] == '0'):
            stateE(n[1:])
        else:
            stateF(n[1:])


def stateF(n):
    if (len(n) == 0):
        print("string accepred")
    else:
        if (n[0] == '1'):
            stateD(n[1:])
        else:
            stateE(n[1:])

def checkstateA(n):
    if (n[0] == '0'):
        stateB(n[1:])
    else:
        stateD(n[1:])


if __name__ == "__main__":
    n = "0100101"
    checkstateA(n)

# Expected output:
String accepted
# find the nth hogben numbers | function returns n - th hogben number ; 
def HogbenNumber(a):
    p = (pow(a, 2) - a + 1)
    return p


N = 10
print(HogbenNumber(N))

# Expected output:
91
# check if left and right shift of any string results into given string | function to check string exist or not as per above approach ; check if any character at position i and i + 2 are not equal , then string doesnot exist ; 
def check_string_exist(S):
    size = len(S)
    check = True
    for i in range(size):
        if S[i] != S[(i + 2) % size]:
            check = False
            break
    if check:
        print("Yes")
    else:
        print("No")


S = "papa"
check_string_exist(S)

# Expected output:
Yes
# cumulative product of digits of all numbers in the given range | function to get product of digits ; function to find the product of digits of all natural numbers in range l to r ; iterate between l to r ; 
def getProduct(n):
    product = 1
    while (n != 0):
        product = product * (n % 10)
        n = int(n / 10)
    return product


def productinRange(l, r):
    if (r - l > 9):
        return 0
    else:
        p = 1
        for i in range(l, r + 1):
            p = p * getProduct(i)
        return p


l = 11
r = 15
print(productinRange(l, r), end='')
l = 1
r = 15
print(productinRange(l, r))

# Expected output:
1200
# check whether the string can be printed using same row of qwerty keypad | function to find the row of the character in the qwerty keypad ; sets to include the characters from the same row of the qwerty keypad ; condition to check the row of the current character of the string ; function to check the characters are from the same row of the qwerty keypad ; 
def checkQwertyRow(x):
    first_row = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=']
    second_row = ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P',
                  '[', ']', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p']
    third_row = ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L',
                 ';', ':', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l']
    fourth_row = [
        'Z',
        'X',
        'C',
        'V',
        'B',
        'N',
        'M',
        ',',
        '.',
        '/',
        'z',
        'x',
        'c',
        'v',
        'b',
        'n',
        'm']
    if (first_row .count(x) > 0):
        return 1
    elif (second_row .count(x) > 0):
        return 2
    elif (third_row .count(x) > 0):
        return 3
    elif (fourth_row .count(x) > 0):
        return 4
    return 0


def checkValidity(str):
    x = str[0]
    row = checkQwertyRow(x)
    for i in range(len(str)):
        x = str[i]
        if (row != checkQwertyRow(x)):
            return False
    return True


str = "GeeksforGeeks"
if (checkValidity(str)):
    print("Yes")
else:
    print("No")

# Expected output:
No
# last digit of sum of numbers in the given range in the fibonacci series | calculate the sum of the first n fibonacci numbers using pisano period ; the first two fibonacci numbers ; base case ; pisano period for % 10 is 60 ; checking the remainder ; the loop will range from 2 to two terms after the remainder ; 
def fib(n):
    f0 = 0
    f1 = 1
    if (n == 0):
        return 0
    if (n == 1):
        return 1
    else:
        rem = n % 60
        if (rem == 0):
            return 0
        for i in range(2, rem + 3):
            f = (f0 + f1) % 60
            f0 = f1
            f1 = f
        s = f1 - 1
        return (s)


if __name__ == '__main__':
    m = 10087887
    n = 2983097899
    final = fib(n) - fib(m - 1)
    print(final % 10)

# Expected output:
5
# find n values of x1 , x2 , ... xn such that x1 < x2 < ... < xn and sin ( x1 ) < sin ( x2 ) < ... < sin ( xn ) | python3 program for the above approach ; function to print all such xi s . t . all xi and sin ( xi ) are strictly increasing ; till n becomes zero ; find the value of sin ( ) using inbuilt function ; increment by 710 ; 

import math


def printSinX(N):
    Xi = 0
    num = 1
    while (N > 0):
        print("X", num, "=", Xi, end=" ")
        print("sin(X", num, ") =", end=" ")
        print("{:.6f}".format(math .sin(Xi)), "")
        num += 1
        Xi += 710
        N = N - 1


N = 5
printSinX(N)

# Expected output:
X 1 = 0 sin(X 1 ) = 0.000000 
X 2 = 710 sin(X 2 ) = 0.000060 
X 3 = 1420 sin(X 3 ) = 0.000121 
X 4 = 2130 sin(X 4 ) = 0.000181 
X 5 = 2840 sin(X 5 ) = 0.000241
# sum of all elements in an array between zeros | function to find the sum between two zeros in the given array arr [ ] ; to store the sum of the element between two zeros ; to store the sum ; find first index of 0 ; traverse the given array arr [ ] ; if 0 occurs then add it to a [ ] ; else add element to the sum ; print all the sum stored in a ; if there is no such element print - 1 ; 
def sumBetweenZero(arr, N):
    i = 0
    A = []
    sum = 0
    for i in range(N):
        if (arr[i] == 0):
            i += 1
            break
    k = i
    for i in range(k, N, 1):
        if (arr[i] == 0):
            A .append(sum)
            sum = 0
        else:
            sum += arr[i]
    for i in range(len(A)):
        print(A[i], end=' ')
    if (len(A) == 0):
        print("-1")


if __name__ == '__main__':
    arr = [1, 0, 3, 4, 0, 4, 4, 0, 2, 1, 4, 0, 3]
    N = len(arr)
    sumBetweenZero(arr, N)

# Expected output:
7 8 7
# find the nth term of the series 2 , 15 , 41 , 80 , 132. . . | recursive function to find nth term ; base case ; recursive call according to nth term of the series ; 
def nthTerm(N):
    if (N == 1):
        return 2
    return ((N - 1) * 13) + nthTerm(N - 1)


if __name__ == '__main__':
    N = 17
    print(nthTerm(N))

# Expected output:
1770
# subsequence pair from given array having all unique and all same elements respectively | function to find the maximum length of subsequences with given property ; to store the frequency ; traverse the array to store the frequency ; m . size ( ) given count of distinct element in arr [ ] ; traverse map to find max frequency ; find the maximum length on the basis of two cases in the approach ; 
def maximumSubsequence(arr, N):
    M = {i: 0 for i in range(100)}
    for i in range(N):
        M[arr[i]] += 1
    distinct_size = len(M)
    maxFreq = 1
    for value in M .values():
        maxFreq = max(maxFreq, value)
    print(max(min(distinct_size, maxFreq - 1), min(distinct_size - 1, maxFreq)))


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

# Expected output:
4
# total length of string from given array of strings composed using given characters | function to count the total length ; unordered_map for keeping frequency of characters ; calculate the frequency ; iterate in the n strings ; iterates in the string ; checks if given character of string string appears in it or not ; adds the length of string if all characters are present ; return the final result ; 
def countCharacters(arr, chars):
    res = 0
    freq = dict()
    for i in range(len(chars)):
        freq[chars[i]] = freq .get(chars[i], 0) + 1
    for st in arr:
        flag = True
        for c in st:
            if (c not in freq):
                flag = False
                break
        if (flag):
            res += len(st)
    return res


if __name__ == '__main__':
    arr = ["hi", "data", "geeksforgeeks"]
    chars = "tiadhae"
    print(countCharacters(arr, chars))

# Expected output:
6
# construct an array of size n in which sum of odd elements is equal to sum of even elements | function to construct the required array ; to construct first half , distinct even numbers ; to construct second half , distinct odd numbers ; calculate the last number of second half so as to make both the halves equal ; function to construct the required array ; check if size is multiple of 4 then array exist ; function call to construct array ; 
def arrayConstruct(N):
    for i in range(2, N + 1, 2):
        print(i, end=" ")
    for i in range(1, N - 1, 2):
        print(i, end=" ")
    print(N - 1 + (N // 2))


def createArray(N):
    if (N % 4 == 0):
        arrayConstruct(N)
    else:
        cout << -1 << endl


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

# Expected output:
2 4 6 8 1 3 5 11
# count of all sub | function to count all substrings ; hashmap to store substrings ; iterate over all substrings ; variable to maintain sum of all characters encountered ; variable to maintain substring till current position ; get position of character in string w ; add weight to current sum ; add current character to substring ; check if sum of characters is <= k insert in hashmap ; 
def distinctSubstring(P, Q, K, N):
    S = set()
    for i in range(N):
        sum = 0
        s = ""
        for j in range(i, N):
            pos = ord(P[j]) - 97
            sum += ord(Q[pos]) - 48
            s += P[j]
            if (sum <= K):
                S .add(s)
            else:
                break
    return len(S)


if __name__ == '__main__':
    S = "abcde"
    W = "12345678912345678912345678"
    K = 5
    N = len(S)
    print(distinctSubstring(S, W, K, N))

# Expected output:
7
# minimum characters required to make a password strong | python3 program to find minimum number of characters required to be added to make a password strong ; function to count minimum number of characters ; create the patterns to search digit , upper case alphabet , lower case alphabet and special character ; if no digits are present ; if no upper case alphabet is present ; if no lower case alphabet is present ; if no special character is is present ; check if the string length after adding the required characters is less than 8 ; add the number of characters to be added ; 

import re


def countCharacters(password):
    count = 0
    digit = re .compile("(\\d)")
    upper = re .compile("([A-Z])")
    lower = re .compile("([a-z])")
    spChar = re .compile("(\\W)")
    if (not re .search(digit, password)):
        count += 1
    if (not re .search(upper, password)):
        count += 1
    if (not re .search(lower, password)):
        count += 1
    if (not re .search(spChar, password)):
        count += 1
    if ((count + len(password)) < 8):
        count = count + 8 - (count + len(password))
    return count


password1 = "Geeksforgeeks"
print(countCharacters(password1))
password2 = "Geeks1"
print(countCharacters(password2))

# Expected output:
2
2
# count all sub | function to find the count of all the substrings with weight of characters atmost k ; hashmap to store all substrings ; iterate over all substrings ; maintain the sum of all characters encountered so far ; maintain the substring till the current position ; get the position of the character in string q ; add weight to current sum ; add current character to substring ; if sum of characters is <= k then insert in into the set ; finding the size of the set ; 
def distinctSubstring(P, Q, K, N):
    S = set()
    for i in range(0, N):
        sum = 0
        s = ''
        for j in range(i, N):
            pos = ord(P[j]) - 97
            sum = sum + ord(Q[pos]) - 48
            s += P[j]
            if (sum <= K):
                S .add(s)
            else:
                break
    return len(S)


P = "abcde"
Q = "12345678912345678912345678"
K = 5
N = len(P)
print(distinctSubstring(P, Q, K, N))

# Expected output:
7
# program to print a hollow triangle inside a triangle | function to print the pattern ; loop for rows ; loop for column ; for printing equal sides of outer triangle ; for printing equal sides of inner triangle ; for printing base of both triangle ; for spacing between the triangle ; 
def printPattern(n):
    for i in range(1, n + 1):
        for j in range(1, 2 * n):
            if (j == (n - i + 1) or j == (n + i - 1)):
                print("* ", end="")
            elif ((i >= 4 and i <= n - 4) and (j == n - i + 4 or j == n + i - 4)):
                print("* ", end="")
            elif (i == n or (i == n - 4 and j >= n - (n - 2 * 4) and j <= n + n - 2 * 4)):
                print("* ", end="")
            else:
                print(" " + " ", end="")
        print()


N = 9
printPattern(N)

# Expected output:
                *                 
              *   *               
            *       *             
          *     *     *           
        *     * * *     *         
      *                   *       
    *                       *     
  *                           *   
* * * * * * * * * * * * * * * * *
# check if a string is made up of k alternating characters | function to check if a string is made up of k alternating characters ; check if all the characters at indices 0 to k - 1 are different ; if that bit is already set in checker , return false ; otherwise update and continue by setting that bit in the checker ; 
def isKAlternating(s, k):
    if (len(s) < k):
        return False
    checker = 0
    for i in range(k):
        bitAtIndex = ord(s[i]) - ord('a')
        if ((checker & (1 << bitAtIndex)) > 0):
            return False
        checker = checker | (1 << bitAtIndex)
    for i in range(k, len(s)):
        if (s[i - k] != s[i]):
            return False
    return True


if __name__ == "__main__":
    st = "acdeac"
    K = 4
    if (isKAlternating(st, K)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes