giulio98/xlcost-single-prompt huggingface dataset:
# print matrix elements from top | function to traverse the matrix diagonally upwards ; store the number of rows ; initialize queue ; push the index of first element i . e . , ( 0 , 0 ) ; get the front element ; pop the element at the front ; insert the element below if the current element is in first column ; insert the right neighbour if it exists ; 
def printDiagonalTraversal(nums):
    m = len(nums)
    q = []
    q .append([0, 0])
    while (len(q) != 0):
        p = q[0]
        q .pop(0)
        print(nums[p[0]][p[1]], end=" ")
        if (p[1] == 0 and p[0] + 1 < m):
            q .append([p[0] + 1, p[1]])
        if (p[1] + 1 < len(nums[p[0]])):
            q .append([p[0], p[1] + 1])


if __name__ == "__main__":
    arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    printDiagonalTraversal(arr)

# Expected output:
1 4 2 7 5 3 8 6 9
# find original sequence from array containing the sequence merged many times in order | function that returns the restored permutation ; list to store the result ; map to mark the elements which are taken in result ; checking if the element is coming first time ; push in result vector ; mark it in the map ; return the answer ; function to print the result ; 
def restore(arr, N):
    result = []
    mp = {}
    for i in range(N):
        if not arr[i] in mp:
            result .append(arr[i])
            mp[arr[i]] = 1
    return result


def print_result(result):
    for i in range(len(result)):
        print(result[i], end=" ")


def main():
    arr = [1, 13, 1, 24, 13, 24, 2, 2]
    N = len(arr)
    print_result(restore(arr, N))


main()

# Expected output:
1 13 24 2
# program to print the pattern 1020304017018019020 * * 50607014015016 * * * * 809012013 * * * * * * 10011. . . | function to find the sum of n integers from 1 to n ; function to print the given pattern ; iterate over [ 0 , n - 1 ] ; sub - pattern - 1 ; sub - pattern - 2 ; count the number of element in rows and sub - pattern 2 and 3 will have same rows ; increment val to print the series 1 , 2 , 3 , 4 , 5 ... ; finally , add the ( n - 1 ) th element i . e . , 5 and increment it by 1 ; initial is used to give the initial value of the row in sub - pattern 3 ; sub - pattern 3 ; skip printing zero at the last ; 
def sum(n):
    return n * (n - 1) // 2


def BSpattern(N):
    Val = 0
    Pthree = 0,
    cnt = 0
    initial = -1
    s = "**"
    for i in range(N):
        cnt = 0
        if (i > 0):
            print(s, end="")
            s += "**"
        for j in range(i, N):
            if (i > 0):
                cnt += 1
            Val += 1
            print(Val, end="")
            print(0, end="")
        if (i == 0):
            Sumbeforelast = sum(Val) * 2
            Pthree = Val + Sumbeforelast + 1
            initial = Pthree
        initial = initial - cnt
        Pthree = initial
        for k in range(i, N):
            print(Pthree, end="")
            Pthree += 1
            if (k != N - 1):
                print(0, end="")
        print()


N = 5
BSpattern(N)

# Expected output:
102030405026027028029030
**6070809022023024025
****10011012019020021
******13014017018
********15016
# check if a number starts with another number or not | function to check if b is a prefix of a or not ; convert numbers into strings ; find the length of s1 and s2 ; base case ; traverse the string s1 and s2 ; if at any index characters are unequal then return false ; return true ; 
def checkprefix(A, B):
    s1 = str(A)
    s2 = str(B)
    n1 = len(s1)
    n2 = len(s2)
    if n1 < n2:
        return False
    for i in range(0, n2):
        if s1[i] != s2[i]:
            return False
    return True


if __name__ == '__main__':
    A = 12345
    B = 12
    result = checkprefix(A, B)
    if result:
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# check if it is possible to reach ( x , y ) from origin in exactly z steps using only plus movements | function to check if it is possible to reach ( x , y ) from origin in exactly z steps ; condition if we can 't reach in z steps ; 
def possibleToReach(x, y, z):
    if (z < abs(x) + abs(y) or (z - abs(x) - abs(y)) % 2):
        print("Not Possible")
    else:
        print("Possible")


if __name__ == '__main__':
    x = 5
    y = 5
    z = 11
    possibleToReach(x, y, z)

# Expected output:
Not Possible
# number of cycles in a polygon with lines from centroid to vertices | function to find the number of cycles ; 
def nCycle(N):
    return (N) * (N - 1) + 1


N = 4
print(nCycle(N))

# Expected output:
13
# sum of consecutive bit differences of first n non | python3 program for the above problem ; recursive function to count the sum of bit differences of numbers from 1 to pow ( 2 , ( i + 1 ) ) - 1 ; base cases ; recursion call if the sum of bit difference of numbers around i are not calculated ; return the sum of bit differences if already calculated ; function to calculate the sum of bit differences up to n ; nearest smaller power of 2 ; remaining numbers ; calculate the count of bit diff ; 

import math
a = [0] * 65


def Count(i):
    if (i == 0):
        return 1
    elif (i < 0):
        return 0
    if (a[i] == 0):
        a[i] = (i + 1) + 2 * Count(i - 1)
        return a[i]
    else:
        return a[i]


def solve(n):
    sum = 0
    while (n > 0):
        i = int(math .log2(n))
        n = n - pow(2, i)
        sum = sum + (i + 1) + Count(i - 1)
    return sum


n = 7
print(solve(n))

# Expected output:
11
# count of total heads and tails after n flips in a coin | function to find count of head and tail ; check if initially all the coins are facing towards head ; check if initially all the coins are facing towards tail ; 

import math


def count_ht(s, N):
    if s == "H":
        h = math .floor(N / 2)
        t = math .ceil(N / 2)
    elif s == "T":
        h = math .ceil(N / 2)
        t = math .floor(N / 2)
    return [h, t]


if __name__ == "__main__":
    C = "H"
    N = 5
    l = count_ht(C, N)
    print("Head = ", l[0])
    print("Tail = ", l[1])

# Expected output:
Head =  2
Tail =  3
# longest palindromic string possible after removal of a substring | function to find the longest palindrome from the start of the string using kmp match ; append s ( reverse of c ) to c ; use kmp algorithm ; function to return longest palindromic string possible from the given string after removal of any substring ; initialize three strings a , b and f ; loop to find longest substrings from both ends which are reverse of each other ; proceed to third step of our approach ; remove the substrings a and b ; find the longest palindromic substring from beginning of c ; find the longest palindromic substring from end of c ; store the maximum of d and e in f ; find the final answer ; 
def findPalindrome(C):
    S = C[::-1]
    C = C[:] + '&' + S
    n = len(C)
    longestPalindrome = [0 for i in range(n)]
    longestPalindrome[0] = 0
    ll = 0
    i = 1
    while (i < n):
        if (C[i] == C[ll]):
            ll += 1
            longestPalindrome[i] = ll
            i += 1
        else:
            if (ll != 0):
                ll = longestPalindrome[ll - 1]
            else:
                longestPalindrome[i] = 0
                i += 1
    ans = C[0:longestPalindrome[n - 1]]
    return ans


def findAns(s):
    A = ""
    B = ""
    F = ""
    i = 0
    j = len(s) - 1
    ll = len(s)
    while (i < j and s[i] == s[j]):
        i = i + 1
        j = j - 1
    if (i > 0):
        A = s[0:i]
        B = s[ll - i:ll]
    if (ll > 2 * i):
        C = s[i:i + (len(s) - 2 * i)]
        D = findPalindrome(C)
        C = C[::-1]
        E = findPalindrome(C)
        if (len(D) > len(E)):
            F = D
        else:
            F = E
    answer = A + F + B
    return answer


if __name__ == "__main__":
    str = "abcdefghiedcba"
    print(findAns(str))

# Expected output:
abcdeiedcba
# find nth term of the series 2 , 3 , 10 , 15 , 26. ... | function to find nth term ; nth term ; 
def nthTerm(N):
    nth = 0
    if (N % 2 == 1):
        nth = (N * N) + 1
    else:
        nth = (N * N) - 1
    return nth


if __name__ == "__main__":
    N = 5
    print(nthTerm(N))

# Expected output:
26
# find the nth term in series 12 , 35 , 81 , 173 , 357 , ... | function to find nth term ; nth term ; 
def nthTerm(N):
    nth = 0
    first_term = 12
    nth = (first_term * (pow(2, N - 1))) + 11 * ((pow(2, N - 1)) - 1)
    return nth


if __name__ == "__main__":
    N = 5
    print(nthTerm(N))

# Expected output:
357
# find nth term of the series 4 , 2 , 2 , 3 , 6 , ... | function to find nth term ; nth term ; 
def nthTerm(N):
    nth = 0
    first_term = 4
    pi = 1
    po = 1
    n = N
    while (n > 1):
        pi *= n - 1
        n -= 1
        po *= 2
    nth = (first_term * pi) // po
    return nth


if __name__ == "__main__":
    N = 5
    print(nthTerm(N))

# Expected output:
6
# find the final number obtained after performing the given operation | python3 implementation of the approach ; function to return the final number obtained after performing the given operation ; find the gcd of the array elements ; 

from math import gcd as __gcd


def finalNum(arr, n):
    result = arr[0]
    for i in arr:
        result = __gcd(result, i)
    return result


arr = [3, 9, 6, 36]
n = len(arr)
print(finalNum(arr, n))

# Expected output:
3
# check whether all the substrings have number of vowels atleast as that of consonants | function that returns true if acter ch is a vowel ; compares two integers according to their digit sum ; check if there are two consecutive consonants ; check if there is any vowel surrounded by two consonants ; 
def isVowel(ch):
    if ch in ['i', 'a', 'e', 'o', 'u']:
        return True
    else:
        return False


def isSatisfied(st, n):
    for i in range(1, n):
        if (isVowel(st[i]) == False and isVowel(st[i - 1]) == False):
            return False
    for i in range(1, n - 1):
        if (isVowel(st[i]) and isVowel(st[i - 1]) ==
                False and isVowel(st[i + 1]) == False):
            return False
    return True


st = "acaba"
n = len(st)
if (isSatisfied(st, n)):
    print("Yes")
else:
    print("No")

# Expected output:
No
# print the longest prefix of the given string which is also the suffix of the same string | returns length of the longest prefix which is also suffix and the two do not overlap . this function mainly is copy of computelpsarray ( ) in kmp algorithm ; length of the previous longest prefix suffix ; loop to calculate lps [ i ] for i = 1 to n - 1 ; this is tricky . consider the example . aaacaaaa and i = 7. the idea is similar to search step . ; if len = 0 ; since we are looking for non overlapping parts ; function that returns the prefix ; get the length of the longest prefix ; stores the prefix ; traverse and add characters ; returns the prefix ; 
def LengthlongestPrefixSuffix(s):
    n = len(s)
    lps = [0 for i in range(n)]
    len1 = 0
    i = 1
    while (i < n):
        if (s[i] == s[len1]):
            len1 += 1
            lps[i] = len1
            i += 1
        else:
            if (len1 != 0):
                len1 = lps[len1 - 1]
            else:
                lps[i] = 0
                i += 1
    res = lps[n - 1]
    if (res > int(n / 2)):
        return int(n / 2)
    else:
        return res


def longestPrefixSuffix(s):
    len1 = LengthlongestPrefixSuffix(s)
    prefix = ""
    for i in range(len1):
        prefix += s[i]
    return prefix


if __name__ == '__main__':
    s = "abcab"
    ans = longestPrefixSuffix(s)
    if (ans == ""):
        print("-1")
    else:
        print(ans)

# Expected output:
ab
# print a number as string of ' a ' and ' b ' in lexicographic order | python 3 program to implement the above approach ; function to calculate number of characters in corresponding string of ' a ' and 'b ; since the minimum number of characters will be 1 ; calculating number of characters ; since k length string can represent at most pow ( 2 , k + 1 ) - 2 that is if k = 4 , it can represent at most pow ( 2 , 4 + 1 ) - 2 = 30 so we have to calculate the length of the corresponding string ; return the length of the corresponding string ; function to print corresponding string of ' a ' and 'b ; find length of string ; since the first number that can be represented by k length string will be ( pow ( 2 , k ) - 2 ) + 1 and it will be aaa ... a , k times , therefore , n will store that how much we have to print ; at a particular time , we have to decide whether we have to print ' a ' or ' b ' , this can be check by calculating the value of pow ( 2 , k - 1 ) ; print new line ; 

from math import pow


def no_of_characters(M):
    k = 1
    while True:
        if pow(2, k+1)-2 < M:
            k += 1
        else:
            break
    return k


def print_string(M):
    k = no_of_characters(M)
    N = M - (pow(2, k) - 2)
    while (k > 0):
        num = pow(2, k - 1)
        if (num >= N):
            print("A", end="")
        else:
            print("B", end="")
            N -= num
        k -= 1
    print("",  end="")


if __name__ == '__main__':
    M = 30
    print_string(M)
    M = 55
    print_string(M)
    M = 100
    print_string(M)

# Expected output:
BBBBBBAAABAABAB
# replace two substrings ( of a string ) with each other | function to return the resultant string ; iterate through all positions i ; current sub - string of length = len ( a ) = len ( b ) ; if current sub - string gets equal to a or b ; update s after replacing a ; update s after replacing b ; return the updated string ; 
def updateString(S, A, B):
    l = len(A)
    i = 0
    while i + l <= len(S):
        curr = S[i:i + l]
        if curr == A:
            new_string = S[0:i] + B + S[i + l:len(S)]
            S = new_string
            i += l - 1
        else:
            new_string = S[0:i] + A + S[i + l:len(S)]
            S = new_string
            i += l - 1
        i += 1
    return S


if __name__ == "__main__":
    S = "aab"
    A = "aa"
    B = "bb"
    print(updateString(S, A, B))

# Expected output:
bbb
# print n 0 s and m 1 s such that no two 0 s and no three 1 s are together | function to print the required pattern ; when condition fails ; when m = n - 1 ; 
def printPattern(n, m):
    if (m > 2 * (n + 1) or m < n - 1):
        print("-1", end="")
    elif (abs(n - m) <= 1):
        while (n > 0 and m > 0):
            print("01", end="")
            n -= 1
            m -= 1
        if (n != 0):
            print("0", end="")
        if (m != 0):
            print("1", end="")
    else:
        while (m - n > 1 and n > 0):
            print("110", end="")
            m = m - 2
            n = n - 1
        while (n > 0):
            print("10", end="")
            n -= 1
            m -= 1
        while (m > 0):
            print("1", end="")
            m -= 1


if __name__ == '__main__':
    n = 4
    m = 8
    printPattern(n, m)

# Expected output:
110110110101
# find the count of strictly decreasing subarrays | function to count the number of strictly decreasing subarrays ; initialize length of current decreasing subarray ; traverse through the array ; if arr [ i + 1 ] is less than arr [ i ] , then increment length ; else update count and reset length ; if last length is more than 1 ; 
def countDecreasing(A, n):
    len = 1
    cnt = 0
    for i in range(n - 1):
        if (A[i + 1] < A[i]):
            len += 1
        else:
            cnt += (((len - 1) * len) // 2)
            len = 1
    if (len > 1):
        cnt += (((len - 1) * len) // 2)
    return cnt


if __name__ == "__main__":
    A = [100, 3, 1, 13]
    n = len(A)
    print(countDecreasing(A, n))

# Expected output:
3
# minimum changes required to make first string substring of second string | python3 program to find the minimum number of characters to be replaced in string s2 , such that s1 is a substring of s2 ; function to find the minimum number of characters to be replaced in string s2 , such that s1 is a substring of s2 ; get the sizes of both strings ; traverse the string s2 ; from every index in s2 , check the number of mis - matching characters in substring of length of s1 ; take minimum of prev and current mis - match ; return answer ; 

import sys


def minimumChar(S1, S2):
    n, m = len(S1), len(S2)
    ans = sys .maxsize
    for i in range(m - n + 1):
        minRemovedChar = 0
        for j in range(n):
            if (S1[j] != S2[i + j]):
                minRemovedChar += 1
        ans = min(minRemovedChar, ans)
    return ans


if __name__ == '__main__':
    S1 = "abc"
    S2 = "paxzk"
    print(minimumChar(S1, S2))

# Expected output:
2
# frequency of a substring in a string | simple python program to count occurrences of pat in txt . ; a loop to slide pat [ ] one by one ; for current index i , check for pattern match ; if pat [ 0. . . m - 1 ] = txt [ i , i + 1 , ... i + m - 1 ] ; 
def countFreq(pat, txt):
    M = len(pat)
    N = len(txt)
    res = 0
    for i in range(N - M + 1):
        j = 0
        while j < M:
            if (txt[i + j] != pat[j]):
                break
            j += 1
        if (j == M):
            res += 1
            j = 0
    return res


if __name__ == '__main__':
    txt = "dhimanman"
    pat = "man"
    print(countFreq(pat, txt))

# Expected output:
2
# optimized naive algorithm for pattern searching | a modified naive pattern searching algorithm that is optimized for the cases when all characters of pattern are different ; for current index i , check for pattern match ; if j == m : if pat [ 0. . . m - 1 ] = txt [ i , i + 1 , ... i + m - 1 ] ; slide the pattern by j ; 
def search(pat, txt):
    M = len(pat)
    N = len(txt)
    i = 0

    while i <= N-M:
        for j in range(M):
            if txt[i + j] != pat[j]:
                break
            j += 1

        if j == M:
            print(("Pattern found at index " + str(i)))
            i = i + M
        elif j == 0:
            i = i + 1
        else:
            i = i + j


txt = "ABCEABCDABCEABCD"
pat = "ABCD"
search(pat, txt)

# Expected output:
Pattern found at index 4
Pattern found at index 12
# find the missing digit in given product of large positive integers | function to find the replaced digit in the product of a * b ; keeps track of the sign of the current digit ; stores the value of a % 11 ; find the value of a mod 11 for large value of a as per the derived formula ; stores the value of b % 11 ; find the value of b mod 11 for large value of a as per the derived formula ; stores the value of c % 11 ; keeps track of the sign of x ; if the current digit is the missing digit , then keep the track of its sign ; find the value of x using the derived equation ; check if x has a negative sign ; return positive equivaluent of x mod 11 ; 
def findMissingDigit(a, b, c):
    w = 1
    a_mod_11 = 0
    for i in range(len(a) - 1, -1, -1):
        a_mod_11 = (a_mod_11 + w * (ord(a[i]) - ord('0'))) % 11
        w = w * -1
    b_mod_11 = 0
    w = 1
    for i in range(len(b) - 1, -1, -1):
        b_mod_11 = (b_mod_11 + w * (ord(b[i]) - ord('0'))) % 11
        w = w * -1
    c_mod_11 = 0
    xSignIsPositive = True
    w = 1
    for i in range(len(c) - 1, -1, -1):
        if (c[i] == 'x'):
            xSignIsPositive = (w == 1)
        else:
            c_mod_11 = (c_mod_11 + w * (ord(c[i]) - ord('0'))) % 11
        w = w * -1
    x = ((a_mod_11 * b_mod_11) - c_mod_11) % 11
    if (not xSignIsPositive):
        x = -x
    return (x % 11 + 11) % 11


A = "123456789"
B = "987654321"
C = "12193263111x635269"
print(findMissingDigit(A, B, C))

# Expected output:
2
# check if a string can be made empty by repeatedly removing given subsequence | function to check if a string can be made empty by removing all subsequences of the form " gfg " or not ; 
def findIfPossible(N, str_):
    countG = 0
    countF = 0
    for i in range(N):
        if str_[i] == 'G':
            countG += 1
        else:
            countF += 1
    if 2 * countF != countG:
        print("NO")
    else:
        id = 0
        flag = True
        for i in range(N):
            if str_[i] == 'G':
                countG -= 1
                id += 1
            else:
                countF -= 1
                id -= 1
            if id < 0:
                flag = False
                break
            if countG < countF:
                flag = False
                break
        if flag:
            print("YES")
        else:
            print("NO")


n = 6
str_ = "GFGFGG"
findIfPossible(n, str_)

# Expected output:
YES
# check whether second string can be formed from characters of first string used any number of times | function to check if str2 can be made by characters of str1 or not ; to store the occurrence of every character ; length of the two strings ; assume that it is possible to compose the string str2 from str1 ; iterate over str1 ; store the presence or every element ; iterate over str2 ; ignore the spaces ; check for the presence of character in str1 ; if it is possible to make str2 from str1 ; 
def isPossible(str1, str2):
    arr = {}
    l1 = len(str1)
    l2 = len(str2)
    possible = True
    for i in range(l1):
        arr[str1[i]] = 1
    for i in range(l2):
        if str2[i] != ' ':
            if arr[str2[i]] == 1:
                continue
            else:
                possible = False
                break
    if possible:
        print("Yes")
    else:
        print("No")


str1 = "we all love geeksforgeeks"
str2 = "we all love geeks"
isPossible(str1, str2)

# Expected output:
Yes
# minimum number of flipping adjacent bits required to make given binary strings equal | function to find the minimum number of inversions required . ; initializing the answer ; iterate over the range ; if s1 [ i ] != s2 [ i ] , then inverse the characters at i snd ( i + 1 ) positions in s1 . ; adding 1 to counter if characters are not same ; 
def find_Min_Inversion(n, s1, s2):
    count = 0
    s1 = list(s1)
    s2 = list(s2)
    for i in range(n - 1):
        if (s1[i] != s2[i]):
            if (s1[i] == '1'):
                s1[i] = '0'
            else:
                s1[i] = '1'
            if (s1[i + 1] == '1'):
                s1[i + 1] = '0'
            else:
                s1[i + 1] = '1'
            count += 1
    s1 = ''.join(s1)
    s2 = ''.join(s2)
    if (s1 == s2):
        return count
    return -1


if __name__ == '__main__':
    n = 4
    s1 = "0101"
    s2 = "1111"
    print(find_Min_Inversion(n, s1, s2))

# Expected output:
2
# longest subsequence with consecutive english alphabets | function to find the length of subsequence starting with character ch ; length of the string ; stores the maximum length ; traverse the given string ; if s [ i ] is required character ch ; increment ans by 1 ; increment character ch ; return the current maximum length with character ch ; function to find the maximum length of subsequence of consecutive characters ; stores the maximum length of consecutive characters ; update ans ; return the maximum length of subsequence ; 
def findSubsequence(S, ch):
    N = len(S)
    ans = 0
    for i in range(N):
        if (S[i] == ch):
            ans += 1
            ch = chr(ord(ch) + 1)
    return ans


def findMaxSubsequence(S):
    ans = 0
    for ch in range(ord('a'), ord('z') + 1):
        ans = max(ans, findSubsequence(S, chr(ch)))
    return ans


if __name__ == '__main__':
    S = "abcabefghijk"
    print(findMaxSubsequence(S))

# Expected output:
7
# minimum number of alternate subsequences required to be removed to empty a binary string | function to find the minimum number of operations to empty a binary string ; stores the resultant number of operations ; stores the number of 0 s ; stores the number of 1 s ; traverse the given string ; to balance 0 with 1 if possible ; increment the value of cn0 by 1 ; to balance 1 with 0 if possible ; increment the value of cn1 ; update the maximum number of unused 0 s and 1 s ; print resultant count ; 
def minOpsToEmptyString(s):
    ans = -10 ** 9
    cn0 = 0
    cn1 = 0
    for i in range(len(s)):
        if (s[i] == '0'):
            if (cn1 > 0):
                cn1 -= 1
            cn0 += 1
        else:
            if (cn0 > 0):
                cn0 -= 1
            cn1 += 1
        ans = max([ans, cn0, cn1])
    print(ans)


if __name__ == '__main__':
    S = "010101"
    minOpsToEmptyString(S)

# Expected output:
1