giulio98/xlcost-single-prompt huggingface dataset:
# reverse the words of a string using stack | function to reverse the words of the given string without using strtok ( ) . ; create an empty string stack ; create an empty temporary string ; traversing the entire string ; push the temporary variable into the stack ; assigning temporary variable as empty ; for the last word of the string ; get the words in reverse order ; 
def reverse(s):
    stc = []
    temp = ""
    for i in range(len(s)):
        if s[i] == ' ':
            stc .append(temp)
            temp = ""
        else:
            temp = temp + s[i]
    stc .append(temp)
    while len(stc) != 0:
        temp = stc[len(stc) - 1]
        print(temp, end=" ")
        stc .pop()
    print()


s = "I Love To Code"
reverse(s)

# Expected output:
Code To Love I
# print an n x m matrix such that each row and column has all the vowels in it | function to print the required matrix ; impossible to generate the required matrix ; store all the vowels ; print the matrix ; print vowels for every index ; shift the vowels by one ; 
def printMatrix(n, m):
    if (n < 5 or m < 5):
        print(-1, end=" ")
        return
    s = "aeiou"
    s = list(s)
    for i in range(n):
        for j in range(m):
            print(s[j % 5], end=" ")
        print()
        c = s[0]
        for i in range(4):
            s[i] = s[i + 1]
        s[4] = c


if __name__ == "__main__":
    n = 5
    m = 5
    printMatrix(n, m)

# Expected output:
a e i o u 
e i o u a 
i o u a e 
o u a e i 
u a e i o
# check if a given string is made up of two alternating characters | function that returns true if the string is made up of two alternating characters ; check if ith character matches with the character at index ( i + 2 ) ; if string consists of a single character repeating itself ; 
def isTwoAlter(s):
    for i in range(len(s) - 2):
        if (s[i] != s[i + 2]):
            return False
    if (s[0] == s[1]):
        return False
    return True


if __name__ == "__main__":
    str = "ABAB"
    if (isTwoAlter(str)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# number of character corrections in the given strings to make them equal | function to return the count of operations required ; to store the count of operations ; no operation required ; one operation is required when any two characters are equal ; two operations are required when none of the characters are equal ; return the minimum count of operations required ; 
def minOperations(n, a, b, c):
    ans = 0
    for i in range(n):
        x = a[i]
        y = b[i]
        z = c[i]
        if (x == y and y == z):
            continue
        elif (x == y or y == z or x == z):
            ans += 1
        else:
            ans += 2
    return ans


if __name__ == '__main__':
    a = "place"
    b = "abcde"
    c = "plybe"
    n = len(a)
    print(minOperations(n, a, b, c))

# Expected output:
6
# check if string can be made lexicographically smaller by reversing any substring | function that returns true if s can be made lexicographically smaller by reversing a sub - string in s ; traverse in the string ; check if s [ i + 1 ] < s [ i ] ; not possible ; 
def check(s):
    n = len(s)
    for i in range(n - 1):
        if (s[i] > s[i + 1]):
            return True
    return False


if __name__ == '__main__':
    s = "geeksforgeeks"
    if (check(s)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# count of sub | function to return the count of required sub - strings ; number of sub - strings from position of current x to the end of str ; to store the number of characters before x ; 
def countSubStr(str, n, x):
    res = 0
    count = 0
    for i in range(n):
        if (str[i] == x):
            res += ((count + 1) * (n - i))
            count = 0
        else:
            count += 1
    return res


str = "abcabc"
n = len(str)
x = 'c'
print(countSubStr(str, n, x))

# Expected output:
15
# count of sub | function to return the count of possible sub - strings of length n ; 
def countSubStr(string, n):
    length = len(string)
    return (length - n + 1)


if __name__ == "__main__":
    string = "geeksforgeeks"
    n = 5
    print(countSubStr(string, n))

# Expected output:
9
# count of sub | function to return the number of sub - strings that do not contain the given character c ; length of the string ; traverse in the string ; if current character is different from the given character ; update the number of sub - strings ; reset count to 0 ; for the characters appearing after the last occurrence of c ; 
def countSubstrings(s, c):
    n = len(s)
    cnt = 0
    Sum = 0
    for i in range(n):
        if (s[i] != c):
            cnt += 1
        else:
            Sum += (cnt * (cnt + 1)) // 2
            cnt = 0
    Sum += (cnt * (cnt + 1)) // 2
    return Sum


s = "baa"
c = 'b'
print(countSubstrings(s, c))

# Expected output:
3
# minimize ascii values sum after removing all occurrences of one character | python3 implementation of the approach ; function to return the minimized sum ; to store the occurrences of each character of the string ; update the occurrence ; calculate the sum ; get the character which is contributing the maximum value to the sum ; count of occurrence of the character multiplied by its ascii value ; return the minimized sum ; 

import sys


def getMinimizedSum(string, length):
    maxVal = -(sys .maxsize - 1)
    sum = 0
    occurrences = [0] * 26
    for i in range(length):
        occurrences[ord(string[i]) - ord('a')] += 1
        sum += ord(string[i])
    for i in range(26):
        count = occurrences[i] * (i + ord('a'))
        maxVal = max(maxVal, count)
    return (sum - maxVal)


if __name__ == "__main__":
    string = "geeksforgeeks"
    length = len(string)
    print(getMinimizedSum(string, length))

# Expected output:
977
# find index i such that prefix of s1 and suffix of s2 till i form a palindrome when concatenated | function that returns true if s is palindrome ; function to return the required index ; copy the ith character in s ; copy all the character of string s2 in temp ; check whether the string is palindrome ; 
def isPalindrome(s):
    i = 0
    j = len(s) - 1
    while (i < j):
        if (s[i] is not s[j]):
            return False
        i += 1
        j -= 1
    return True


def getIndex(S1, S2, n):
    S = ""
    for i in range(n):
        S = S + S1[i]
        Temp = ""
        for j in range(i + 1, n):
            Temp += S2[j]
        if (isPalindrome(S + Temp)):
            return i
    return -1


S1 = "abcdf"
S2 = "sfgba"
n = len(S1)
print(getIndex(S1, S2, n))

# Expected output:
1
# find index i such that prefix of s1 and suffix of s2 till i form a palindrome when concatenated | function that returns true if the sub - string starting from index i and ending at index j is a palindrome ; function to get the required index ; start comparing the two strings from both ends . ; break from the loop at first mismatch ; if it is possible to concatenate the strings to form palindrome , return index ; if remaining part for s2 is palindrome ; if remaining part for s1 is palindrome ; if not possible , return - 1 ; 
def isPalindrome(s, i, j):
    while (i < j):
        if (s[i] != s[j]):
            return False
        i += 1
        j -= 1
    return True


def getIndex(s1, s2, length):
    i = 0
    j = length - 1
    while (i < j):
        if (s1[i] != s2[j]):
            break
        i += 1
        j -= 1
    if (i == j):
        return i - 1
    elif (isPalindrome(s2, i, j)):
        return i - 1
    elif (isPalindrome(s1, i, j)):
        return j
    return -1


if __name__ == "__main__":
    s1 = "abcdf"
    s2 = "sfgba"
    length = len(s1)
    print(getIndex(s1, s2, length))

# Expected output:
1
# acronym words | function to return the number of strings that can be an acronym for other strings ; frequency array to store the frequency of the first character of every string in the array ; to store the count of required strings ; current word ; frequency array to store the frequency of each of the character of the current string ; check if the frequency of every character in the current string is <= its value in freq [ ] ; first character of the current string ; 
def count_acronym(n, arr):
    freq = [0] * 26
    for i in range(n):
        freq[ord(arr[i][0]) - ord('a')] += 1
    cnt = 0
    for i in range(n):
        st = arr[i]
        num = [0] * 26
        for j in range(len(st)):
            num[ord(st[j]) - ord('a')] += 1
        flag = True
        for j in range(1, 26):
            if num[j] > freq[j]:
                flag = False
                break
        x = ord(st[0]) - ord('a')
        if freq[x] - 1 < num[x]:
            flag = False
        if flag:
            cnt += 1
    return cnt


if __name__ == "__main__":
    arr = ["abc", "bcad", "cabd", "cba", "dzzz"]
    n = 5
    print(count_acronym(n, arr))

# Expected output:
2
# sub | function that returns true if every lowercase character appears atmost once ; every character frequency must be not greater than one ; function that returns the modified good string if possible ; if the length of the string is less than n ; sub - strings of length 26 ; to store frequency of each character ; get the frequency of each character in the current sub - string ; check if we can get sub - string containing the 26 characters all ; find which character is missing ; fill with missing characters ; find the next missing character ; return the modified good string ; 
def valid(cnt):
    for i in range(0, 26):
        if cnt[i] >= 2:
            return False
    return True


def getGoodString(s, n):
    if n < 26:
        return "-1"
    for i in range(25, n):
        cnt = [0] * 26
        for j in range(i, i - 26, -1):
            if s[j] != '?':
                cnt[ord(s[j]) - ord('a')] += 1
        if valid(cnt):
            cur = 0
            while cur < 26 and cnt[cur] > 0:
                cur += 1
            for j in range(i - 25, i + 1):
                if s[j] == '?':
                    s[j] = chr(cur + ord('a'))
                    cur += 1
                    while cur < 26 and cnt[cur] > 0:
                        cur += 1
            return ''.join(s)
    return "-1"


if __name__ == "__main__":
    s = "abcdefghijkl?nopqrstuvwxy?"
    n = len(s)
    print(getGoodString(list(s), n))

# Expected output:
abcdefghijklmnopqrstuvwxyz
# modify the string by swapping continuous vowels or consonants | function to check if a character is a vowel ; function to swap two consecutively repeated vowels or consonants ; traverse through the length of the string ; check if the two consecutive characters are vowels or consonants ; swap the two characters ; 
def isVowel(c):
    c = c .lower()
    if (c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u'):
        return True
    return False


def swapRepeated(string):
    for i in range(len(string) - 1):
        if ((isVowel(string[i]) and isVowel(string[i + 1]))
                or (not (isVowel(string[i])) and not (isVowel(string[i + 1])))):
            (string[i], string[i + 1]) = (string[i + 1], string[i])
    string = "".join(string)
    return string


if __name__ == "__main__":
    string = "geeksforgeeks"
    print(swapRepeated(list(string)))

# Expected output:
geesfkogreesk
# find the lexicographically largest palindromic subsequence of a string | function to find the largest palindromic subsequence ; find the largest character ; append all occurrences of largest character to the resultant string ; 
def largestPalinSub(s):
    res = ""
    mx = s[0]
    for i in range(1, len(s)):
        mx = max(mx, s[i])
    for i in range(0, len(s)):
        if s[i] == mx:
            res += s[i]
    return res


if __name__ == "__main__":
    s = "geeksforgeeks"
    print(largestPalinSub(s))

# Expected output:
ss
# generate lexicographically smallest string of 0 , 1 and 2 with adjacent swaps allowed | function to print the required string ; count number of 1 s ; to check if the all the 1 s have been used or not ; print all the 1 s if any 2 is encountered ; if str1 [ i ] = 0 or str1 [ i ] = 2 ; if 1 s are not printed yet ; 
def printString(Str1, n):
    ones = 0
    for i in range(n):
        if (Str1[i] == '1'):
            ones += 1
    used = False
    for i in range(n):
        if (Str1[i] == '2' and used == False):
            used = 1
            for j in range(ones):
                print("1", end="")
        if (Str1[i] != '1'):
            print(Str1[i], end="")
    if (used == False):
        for j in range(ones):
            print("1", end="")


Str1 = "100210"
n = len(Str1)
printString(Str1, n)

# Expected output:
001120
# k length words that can be formed from given characters without repetition | python3 implementation of the approach ; function to return the required count ; to store the count of distinct characters in str ; traverse str character by character ; if current character is appearing for the first time in str ; increment the distinct character count ; update the appearance of the current character ; since p ( n , r ) = n ! / ( n - r ) ! ; return the answer ; 

import math as mt


def findPermutation(string, k):
    has = [False for i in range(26)]
    cnt = 0
    for i in range(len(string)):
        if (has[ord(string[i]) - ord('a')] == False):
            cnt += 1
            has[ord(string[i]) - ord('a')] = True
    ans = 1
    for i in range(2, cnt + 1):
        ans *= i
    for i in range(cnt - k, 1, -1):
        ans //= i
    return ans


string = "geeksforgeeks"
k = 4
print(findPermutation(string, k))

# Expected output:
840
# find the number in a range having maximum product of the digits | returns the product of digits of number x ; this function returns the number having maximum product of the digits ; converting both integers to strings ; let the current answer be r ; stores the current number having current digit one less than current digit in b ; replace all following digits with 9 to maximise the product ; convert string to number ; check if it lies in range and its product is greater than max product ; 
def product(x):
    prod = 1
    while (x):
        prod *= (x % 10)
        x //= 10
    return prod


def findNumber(l, r):
    a = str(l)
    b = str(r)
    ans = r
    for i in range(len(b)):
        if (b[i] == '0'):
            continue
        curr = list(b)
        curr[i] = str(((ord(curr[i]) - ord('0')) - 1) + ord('0'))
        for j in range(i + 1, len(curr)):
            curr[j] = str(ord('9'))
        num = 0
        for c in curr:
            num = num * 10 + (int(c) - ord('0'))
        if (num >= l and product(ans) < product(num)):
            ans = num
    return ans


if __name__ == "__main__":
    l, r = 1, 10
    print(findNumber(l, r))
    l, r = 51, 62
    print(findNumber(l, r))

# Expected output:
9
59
# longest ordered subsequence of vowels | python3 program to find the longest subsequence of vowels in the specified order ; mapping values for vowels ; function to check if given subsequence contains all the vowels or not ; not contain vowel ; function to find the longest subsequence of vowels in the given string in specified order ; if we have reached the end of the string , return the subsequence if it is valid , else return an empty list ; if there is no vowel in the subsequence yet , add vowel at current index if it is ' a ' , else move on to the next character in the string ; if the last vowel in the subsequence until now is same as the vowel at current index , add it to the subsequence ; if the vowel at the current index comes right after the last vowel in the subsequence , we have two options : either to add the vowel in the subsequence , or move on to next character . we choose the one which gives the longest subsequence . ; 

vowels = ['a', 'e', 'i', 'o', 'u']
mapping = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}


def isValidSequence(subList):
    for vowel in vowels:
        if vowel not in subList:
            return False
    return True


def longestSubsequence(string, subList, index):
    if index == len(string):
        if isValidSequence(subList):
            return subList
        else:
            return []
    else:
        if len(subList) == 0:
            if string[index] != 'a':
                return longestSubsequence(string, subList, index + 1)
            else:
                return longestSubsequence(string, subList + [string[index]], index + 1)
        elif mapping[subList[-1]] == mapping[string[index]]:
            return longestSubsequence(string, subList + [string[index]], index + 1)
        elif (mapping[subList[-1]] + 1) == mapping[string[index]]:
            sub1 = longestSubsequence(
                string, subList + [string[index]], index + 1)
            sub2 = longestSubsequence(string, subList, index + 1)
            if len(sub1) > len(sub2):
                return sub1
            else:
                return sub2
        else:
            return longestSubsequence(string, subList, index + 1)


if __name__ == "__main__":
    string = "aeiaaioooauuaeiou"
    subsequence = longestSubsequence(string, [], 0)
    if len(subsequence) == 0:
        print("No subsequence possible")
    else:
        print(subsequence)

# Expected output:
a, e, i, i, o, o, o, u, u, u
# concatenate suffixes of a string | function to print the expansion of the string ; take sub - string from i to n - 1 ; print the sub - string ; 
def printExpansion(str):
    for i in range(len(str) - 1, -1, -1):
        for j in range(i, len(str)):
            print(str[j], end="")


str = "geeks"
printExpansion(str)

# Expected output:
sksekseeksgeeks
# construct a binary string following the given constraints | function to print a binary string which has ' a ' number of 0 ' s , ▁ ' b ' ▁ number ▁ of ▁ 1' s and there are at least ' x ' indices such that s [ i ] != s [ i + 1 ] ; divide index value by 2 and store it into d ; if index value x is even and x / 2 is not equal to a ; loop for d for each d print 10 ; subtract d from a and b ; loop for b to print remaining 1 's ; loop for a to print remaining 0 's ; 
def constructBinString(a, b, x):
    d = x // 2
    if x % 2 == 0 and x // 2 != a:
        d -= 1
        print("0", end="")
        a -= 1
    for i in range(d):
        print("10", end="")
    a = a - d
    b = b - d
    for i in range(b):
        print("1", end="")
    for i in range(a):
        print("0", end="")


if __name__ == "__main__":
    a, b, x = 4, 3, 2
    constructBinString(a, b, x)

# Expected output:
0111000
# check if every group of a ' s ▁ is ▁ followed ▁ by ▁ a ▁ group ▁ of ▁ b ' s of same length | function to match whether there are always n consecutive b ' s ▁ followed ▁ by ▁ n ▁ consecutive ▁ a ' s throughout the string ; traverse through the string ; count a 's in current segment ; count b 's in current segment ; if both counts are not same . ; 
def matchPattern(s):
    count = 0
    n = len(s)
    i = 0
    while (i < n):
        while (i < n and s[i] == 'a'):
            count += 1
            i = +1
        while (i < n and s[i] == 'b'):
            count -= 1
            i += 1
        if (count != 0):
            return False
    return True


s = "bb"
if (matchPattern(s)):
    print("Yes")
else:
    print("No")

# Expected output:
No
# length of longest consecutive ones by at most one swap in a binary string | function to calculate the length of the longest consecutive 1 's ; to count all 1 's in the string ; to store cumulative 1 's ; counting cumulative 1 's from left ; if 0 then start new cumulative one from that i ; perform step 3 of the approach ; step 3 ; 
def maximum_one(s, n):
    cnt_one = 0
    cnt, max_cnt = 0, 0
    for i in range(n):
        if (s[i] == '1'):
            cnt_one += 1
            cnt += 1
        else:
            max_cnt = max(max_cnt, cnt)
            cnt = 0
    max_cnt = max(max_cnt, cnt)
    left = [0] * n
    right = [0] * n
    if (s[0] == '1'):
        left[0] = 1
    else:
        left[0] = 0
    if (s[n - 1] == '1'):
        right[n - 1] = 1
    else:
        right[n - 1] = 0
    for i in range(1, n):
        if (s[i] == '1'):
            left[i] = left[i - 1] + 1
        else:
            left[i] = 0
    for i in range(n - 2, -1, -1):
        if (s[i] == '1'):
            right[i] = right[i + 1] + 1
        else:
            right[i] = 0
    for i in range(1, n - 1):
        if (s[i] == '0'):
            sum = left[i - 1] + right[i + 1]
            if (sum < cnt_one):
                max_cnt = max(max_cnt, sum + 1)
            else:
                max_cnt = max(max_cnt, sum)
    return max_cnt


if __name__ == "__main__":
    s = "111011101"
    print(maximum_one(s, len(s)))

# Expected output:
7
# maximum length substring with highest frequency in a string | function to return maximum occurred substring of a string ; size of string ; to store maximum frequency ; to store string which has maximum frequency ; return substring which has maximum freq ; 
def MaxFreq(s):
    n = len(s)
    m = dict()
    for i in range(n):
        string = ''
        for j in range(i, n):
            string += s[j]
            if string in m .keys():
                m[string] += 1
            else:
                m[string] = 1
    maxi = 0
    maxi_str = ''
    for i in m:
        if m[i] > maxi:
            maxi = m[i]
            maxi_str = i
        elif m[i] == maxi:
            ss = i
            if len(ss) > len(maxi_str):
                maxi_str = ss
    return maxi_str


string = "ababecdecd"
print(MaxFreq(string))

# Expected output:
ecd
# lexicographically smallest substring with maximum occurrences containing a ' s ▁ and ▁ b ' s only | function to find the lexicographically smallest substring in a given string with maximum frequency and contains a ' s ▁ and ▁ b ' s only . ; to store frequency of digits ; size of string ; take lexicographically larger digit in b ; get frequency of each character ; if no such string exits ; maximum frequency ; 
def maxFreq(s, a, b):
    fre = [0 for i in range(10)]
    n = len(s)
    if (a > b):
        swap(a, b)
    for i in range(0, n, 1):
        a = ord(s[i]) - ord('0')
        fre[a] += 1
    if (fre[a] == 0 and fre[b] == 0):
        return -1
    elif (fre[a] >= fre[b]):
        return a
    else:
        return b


if __name__ == '__main__':
    a = 4
    b = 7
    s = "47744"
    print(maxFreq(s, a, b))

# Expected output:
4
# minimum steps to convert one binary string to other only using negation | function to find the minimum steps to convert string a to string b ; list to mark the positions needed to be negated ; if two character are not same then they need to be negated ; to count the blocks of 1 ; to count the number of 1 ' s ▁ in ▁ each ▁ ▁ block ▁ of ▁ 1' s ; for the last block of 1 's ; 
def convert(n, a, b):
    l = [0] * n
    for i in range(n):
        if (a[i] != b[i]):
            l[i] = 1
    cc = 0
    vl = 0
    for i in range(n):
        if (l[i] == 0):
            if (vl != 0):
                cc += 1
            vl = 0
        else:
            vl += 1
    if (vl != 0):
        cc += 1
    print(cc)


a = "101010"
b = "110011"
n = len(a)
convert(n, a, b)

# Expected output:
2
# generate a sequence with the given operations | function to find minimum required permutation ; 
def StringMatch(S):
    lo, hi = 0, len(S)
    ans = []
    for x in S:
        if x == 'I':
            ans .append(lo)
            lo += 1
        else:
            ans .append(hi)
            hi -= 1
    return ans + [lo]


S = "IDID"
print(StringMatch(S))

# Expected output:
[0, 4, 1, 3, 2]
# number of ways to swap two bit of s1 so that bitwise or of s1 and s2 changes | function to find number of ways ; initialise result that store no . of swaps required ; traverse both strings and check the bits as explained ; calculate result ; 
def countWays(s1, s2, n):
    a = b = c = d = 0
    result = 0
    for i in range(0, n, 1):
        if (s2[i] == '0'):
            if (s1[i] == '0'):
                c += 1
            else:
                d += 1
        else:
            if (s1[i] == '0'):
                a += 1
            else:
                b += 1
    result = a * d + b * c + c * d
    return result


if __name__ == '__main__':
    n = 5
    s1 = "01011"
    s2 = "11001"
    print(countWays(s1, s2, n))

# Expected output:
4