giulio98/xlcost-single-prompt huggingface dataset:
# capitalize the first and last character of each word in a string | python3 program to capitalise the first and last character of each word in a string . ; create an equivalent char array of given string ; k stores index of first character and i is going to store index of last character . ; check if the character is a small letter if yes , then capitalise ; 
def FirstAndLast(string):
    ch = list(string)
    i = 0
    while i < len(ch):
        k = i
        while (i < len(ch) and ch[i] != ' '):
            i += 1
        if (ord(ch[k]) >= 97 and ord(ch[k]) <= 122):
            ch[k] = chr(ord(ch[k]) - 32)
        else:
            ch[k] = ch[k]
        if (ord(ch[i - 1]) >= 90 and ord(ch[i - 1]) <= 122):
            ch[i - 1] = chr(ord(ch[i - 1]) - 32)
        else:
            ch[i - 1] = ch[i - 1]
        i += 1
    return "".join(ch)


if __name__ == "__main__":
    string = "Geeks for Geeks"
    print(string)
    print(FirstAndLast(string))

# Expected output:
Geeks for Geeks
GeekS FoR GeekS
# find the number of players who roll the dice when the dice output sequence is given | function to return the number of players ; initialize cnt as 0 ; iterate in the string ; check for numbers other than x ; 
def findM(s, x):
    cnt = 0
    for i in range(len(s)):
        if (ord(s[i]) - ord('0') != x):
            cnt += 1
    return cnt


if __name__ == '__main__':
    s = "3662123"
    x = 6
    print(findM(s, x))

# Expected output:
5
# print the first and last character of each word in a string | python3 program to print the first and last character of each word in a string ; function to print the first and last character of each word . ; if it is the first word of the string then print it . ; if it is the last word of the string then also print it . ; if there is a space print the successor and predecessor to space . ; 
def FirstAndLast(string):
    for i in range(len(string)):
        if i == 0:
            print(string[i], end="")
        if i == len(string) - 1:
            print(string[i], end="")
        if string[i] == " ":
            print(string[i - 1], string[i + 1], end="")


if __name__ == "__main__":
    string = "Geeks for Geeks"
    FirstAndLast(string)

# Expected output:
Gs fr Gs
# find the longest sub | function to find longest prefix suffix ; to store longest prefix suffix ; length of the previous longest prefix suffix ; lps [ 0 ] is always 0 ; loop calculates lps [ i ] for i = 1 to n - 1 ; ( pat [ i ] != pat [ len ] ) ; if len = 0 ; function to find the longest substring which is prefix as well as a sub - of s [ 1. . . n - 2 ] ; find longest prefix suffix ; if lps of n - 1 is zero ; at any position lps [ i ] equals to lps [ n - 1 ] ; if answer is not possible ; 
def compute_lps(s):
    n = len(s)
    lps = [0 for i in range(n)]
    Len = 0
    lps[0] = 0
    i = 1
    while (i < n):
        if (s[i] == s[Len]):
            Len += 1
            lps[i] = Len
            i += 1
        else:
            if (Len != 0):
                Len = lps[Len - 1]
            else:
                lps[i] = 0
                i += 1
    return lps


def Longestsubstring(s):
    lps = compute_lps(s)
    n = len(s)
    if (lps[n - 1] == 0):
        print(-1)
        exit()
    for i in range(0, n - 1):
        if (lps[i] == lps[n - 1]):
            print(s[0:lps[i]])
            exit()
    if (lps[lps[n - 1] - 1] == 0):
        print(-1)
    else:
        print(s[0:lps[lps[n - 1] - 1]])


s = "fixprefixsuffix"
Longestsubstring(s)

# Expected output:
fix
# pairs of strings which on concatenating contains each character of " string " | python3 implementation of the approach ; function to return the bitmask for the string ; function to return the count of pairs ; bitmask [ i ] will store the count of strings from the array whose bitmask is i ; to store the count of pairs ; max - 1 = 63 i . e . 111111 in binary ; arr [ i ] cannot make s pair with itself i . e . ( arr [ i ] , arr [ i ] ) ; 

MAX = 64


def getBitmask(s):
    temp = 0
    for j in range(len(s)):
        if (s[j] == 's'):
            temp = temp | 1
        elif (s[j] == 't'):
            temp = temp | 2
        elif (s[j] == 'r'):
            temp = temp | 4
        elif (s[j] == 'i'):
            temp = temp | 8
        elif (s[j] == 'n'):
            temp = temp | 16
        elif (s[j] == 'g'):
            temp = temp | 32
    return temp


def countPairs(arr, n):
    bitMask = [0 for i in range(MAX)]
    for i in range(n):
        bitMask[getBitmask(arr[i])] += 1
    cnt = 0
    for i in range(MAX):
        for j in range(i, MAX):
            if ((i | j) == (MAX - 1)):
                if (i == j):
                    cnt += ((bitMask[i] * bitMask[i] - 1) // 2)
                else:
                    cnt += (bitMask[i] * bitMask[j])
    return cnt


arr = ["strrr", "string", "gstrin"]
n = len(arr)
print(countPairs(arr, n))

# Expected output:
3
# count of pairs of strings which differ in exactly one position | function to return the count of same pairs ; function to return total number of strings which satisfy required condition ; dictionary changed will store strings with wild cards dictionary same will store strings that are equal ; iterating for all strings in the given array ; if we found the string then increment by 1 else it will get default value 0 ; iterating on a single string ; incrementing the string if found else it will get default value 0 ; return counted pairs - equal pairs ; 
def pair_count(d):
    return sum((i * (i - 1)) // 2 for i in d .values())


def Difference(array, m):
    changed, same = {}, {}
    for s in array:
        same[s] = same .get(s, 0) + 1
        for i in range(m):
            t = s[:i]+'#'+s[i + 1:]
            changed[t] = changed .get(t, 0) + 1
    return pair_count(changed) - pair_count(same) * m


if __name__ == "__main__":
    n, m = 3, 3
    array = ["abc", "abd", "bbd"]
    print(Difference(array, m))

# Expected output:
2
# number of ways in which the substring in range [ l , r ] can be formed using characters out of the range | function to return the number of ways to form the sub - string ; initialize a hash - table with 0 ; iterate in the string and count the frequency of characters that do not lie in the range l and r ; out of range characters ; stores the final number of ways ; iterate for the sub - string in the range l and r ; if exists then multiply the number of ways and decrement the frequency ; if does not exist the sub - string cannot be formed ; return the answer ; 
def calculateWays(s, n, l, r):
    freq = [0 for i in range(26)]
    for i in range(n):
        if (i < l or i > r):
            freq[ord(s[i]) - ord('a')] += 1
    ways = 1
    for i in range(l, r + 1, 1):
        if (freq[ord(s[i]) - ord('a')]):
            ways = ways * freq[ord(s[i]) - ord('a')]
            freq[ord(s[i]) - ord('a')] -= 1
        else:
            ways = 0
            break
    return ways


if __name__ == '__main__':
    s = "cabcaab"
    n = len(s)
    l = 1
    r = 3
    print(calculateWays(s, n, l, r))

# Expected output:
2
# program to find the kth character after decrypting a string | function to print kth character of string s after decrypting it ; get the length of string ; initialise pointer to character of input string to zero ; total length of resultant string ; traverse the string from starting and check if each character is alphabet then increment total_len ; if total_leg equal to k then return string else increment i ; parse the number ; update next_total_len ; get the position of kth character ; position not found then update position with total_len ; recursively find the kth position ; else update total_len by next_total_len ; return - 1 if character not found ; 
def findKthChar(s, k):
    len1 = len(s)
    i = 0
    total_len = 0
    while (i < len1):
        if (s[i].isalpha()):
            total_len += 1
            if (total_len == k):
                return s[i]
            i += 1
        else:
            n = 0
            while (i < len1 and s[i].isalpha() == False):
                n = n * 10 + (ord(s[i]) - ord('0'))
                i += 1
            next_total_len = total_len * n
            if (k <= next_total_len):
                pos = k % total_len
                if (pos == 0):
                    pos = total_len
                return findKthChar(s, pos)
            else:
                total_len = next_total_len
    return -1


if __name__ == '__main__':
    s = "ab2c3"
    k = 5
    print(findKthChar(s, k))

# Expected output:
c
# convert the ascii value sentence to its equivalent string | function to print the character sequence for the given ascii sentence ; append the current digit ; if num is within the required range ; convert num to char ; reset num to 0 ; 
def asciiToSentence(string, length):
    num = 0
    for i in range(length):
        num = num * 10 + (ord(string[i]) - ord('0'))
        if (num >= 32 and num <= 122):
            ch = chr(num)
            print(ch, end="")
            num = 0


if __name__ == "__main__":
    string = "7110110110711510211111471101101107115"
    length = len(string)
    asciiToSentence(string, length)

# Expected output:
GeeksforGeeks
# distinct state codes that appear in a string as contiguous sub | function to return the count of distinct state codes ; insert every sub - string of length 2 in the set ; return the size of the set ; 
def countDistinctCode(string):
    codes = set()
    for i in range(0, len(string) - 1):
        codes .add(string[i:i + 2])
    return len(codes)


if __name__ == "__main__":
    string = "UPUP"
    print(countDistinctCode(string))

# Expected output:
2
# count of buttons pressed in a keypad mobile | array to store how many times a button has to be pressed for typing a particular character ; function to return the count of buttons pressed to type the given string ; count the key presses ; return the required count ; 

arr = [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3,
       1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 1, 2, 3, 4]


def countKeyPressed(string, length):
    count = 0
    for i in range(length):
        count += arr[ord(string[i]) - ord('a')]
    return count


if __name__ == "__main__":
    string = "abcdef"
    length = len(string)
    print(countKeyPressed(string, length))

# Expected output:
12
# first string from the given array whose reverse is also present in the same array | function that returns true if s1 is equal to reverse of s2 ; if both the strings differ in length ; in case of any character mismatch ; function to return the first word whose reverse is also present in the array ; check every string ; pair with every other string appearing after the current string ; if first string is equal to the reverse of the second string ; no such string exists ; 
def isReverseEqual(s1, s2):
    if len(s1) != len(s2):
        return False
    l = len(s1)
    for i in range(l):
        if s1[i] != s2[l - i - 1]:
            return False
    return True


def getWord(str, n):
    for i in range(n - 1):
        for j in range(i + 1, n):
            if (isReverseEqual(str[i], str[j])):
                return str[i]
    return "-1"


if __name__ == "__main__":
    str = ["geeks", "for", "skeeg"]
    print(getWord(str, 3))

# Expected output:
geeks
# check if the given string is k | function that returns true if sub - string of length k starting at index i is also a prefix of the string ; k length sub - string cannot start at index i ; character mismatch between the prefix and the sub - string starting at index i ; function that returns true if str is k - periodic ; check whether all the sub - strings str [ 0 , k - 1 ] , str [ k , 2 k - 1 ] ... are equal to the k length prefix of the string ; 
def isPrefix(string, length, i, k):
    if i + k > length:
        return False
    for j in range(0, k):
        if string[i] != string[j]:
            return False
        i += 1
    return True


def isKPeriodic(string, length, k):
    for i in range(k, length, k):
        if isPrefix(string, length, i, k) == False:
            return False
    return True


if __name__ == "__main__":
    string = "geeksgeeks"
    length = len(string)
    k = 5
    if isKPeriodic(string, length, k):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# minimum number of letters needed to make a total of n | function to return the minimum letters required to make a total of n ; 
def minLettersNeeded(n):
    if n % 26 == 0:
        return (n // 26)
    else:
        return ((n // 26) + 1)


n = 52
print(minLettersNeeded(n))

# Expected output:
2
# find the first maximum length even word from a string | function to find maximum length even word ; to store length of current word . ; to store length of maximum length word . ; to store starting index of maximum length word . ; if current character is space then word has ended . check if it is even length word or not . if yes then compare length with maximum length found so far . ; set currlen to zero for next word . ; update length of current word . ; check length of last word . ; if no even length word is present then return - 1. ; 
def findMaxLenEven(str):
    n = len(str)
    i = 0
    currlen = 0
    maxlen = 0
    st = -1
    while (i < n):
        if (str[i] == ' '):
            if (currlen % 2 == 0):
                if (maxlen < currlen):
                    maxlen = currlen
                    st = i - currlen
            currlen = 0
        else:
            currlen += 1
        i += 1
    if (currlen % 2 == 0):
        if (maxlen < currlen):
            maxlen = currlen
            st = i - currlen
    if (st == -1):
        print("trie")
        return "-1"
    return str[st:st + maxlen]


if __name__ == "__main__":
    str = "this is a test string"
    print(findMaxLenEven(str))

# Expected output:
string
# minimum length substring with exactly k distinct characters | function to find minimum length substring having exactly k distinct character . ; starting index of sliding window . ; ending index of sliding window . ; to store count of character . ; to store count of distinct character in current sliding window . ; to store length of current sliding window . ; to store minimum length . ; to store starting index of minimum length substring . ; increment count of current character if this count is one then a new distinct character is found in sliding window . ; if number of distinct characters is is greater than k , then move starting point of sliding window forward , until count is k . ; remove characters from the beginning of sliding window having count more than 1 to minimize length . ; compare length with minimum length and update if required . ; return minimum length substring . ; 
def findMinLenStr(str, k):
    n = len(str)
    st = 0
    end = 0
    cnt = [0] * 26
    distEle = 0
    currlen = 0
    minlen = n
    startInd = -1
    while (end < n):
        cnt[ord(str[end]) - ord('a')] += 1
        if (cnt[ord(str[end]) - ord('a')] == 1):
            distEle += 1
        if (distEle > k):
            while (st < end and distEle > k):
                if (cnt[ord(str[st]) - ord('a')] == 1):
                    distEle -= 1
                cnt[ord(str[st]) - ord('a')] -= 1
                st += 1
        if (distEle == k):
            while (st < end and cnt[ord(str[st]) - ord('a')] > 1):
                cnt[ord(str[st]) - ord('a')] -= 1
                st += 1
            currlen = end - st + 1
            if (currlen < minlen):
                minlen = currlen
                startInd = st
        end += 1
    return str[startInd:startInd + minlen]


if __name__ == "__main__":
    str = "efecfefd"
    k = 4
    print(findMinLenStr(str, k))

# Expected output:
cfefd
# minimum number of replacements to make the binary string alternating | set 2 | function to return the minimum number of characters of the given binary string to be replaced to make the string alternating ; if there is 1 at even index positions ; if there is 0 at odd index positions ; 
def minReplacement(s, length):
    ans = 0
    for i in range(0, length):
        if i % 2 == 0 and s[i] == '1':
            ans += 1
        if i % 2 == 1 and s[i] == '0':
            ans += 1
    return min(ans, length - ans)


if __name__ == "__main__":
    s = "1100"
    length = len(s)
    print(minReplacement(s, length))

# Expected output:
2
# deletions of "01" or "10" in binary string to make it free from "01" or "10" | function to return the count of deletions of sub - strings "01" or "10" ; to store the count of 0 s and 1 s ; 
def substrDeletion(string, length):
    count0 = 0
    count1 = 0
    for i in range(length):
        if (string[i] == '0'):
            count0 += 1
        else:
            count1 += 1
    return min(count0, count1)


if __name__ == "__main__":
    string = "010"
    length = len(string)
    print(substrDeletion(string, length))

# Expected output:
1
# group consecutive characters of same type in a string | function to return the modified string ; store original string ; remove all white spaces ; to store the resultant string ; traverse the string ; group upper case characters ; group numeric characters ; group arithmetic operators ; return the resultant string ; 
def groupCharacters(s, l):
    temp = ""
    for i in range(l):
        if (s[i] != ' '):
            temp = temp + s[i]
    l = len(temp)
    ans = ""
    i = 0
    while (i < l):
        if (ord(temp[i]) >= ord('A') and ord(temp[i]) <= ord('Z')):
            while (
                i < l and ord(
                    temp[i]) >= ord('A') and ord(
                    temp[i]) <= ord('Z')):
                ans = ans + temp[i]
                i += 1
            ans = ans + " "
        elif (ord(temp[i]) >= ord('0') and ord(temp[i]) <= ord('9')):
            while (
                i < l and ord(
                    temp[i]) >= ord('0') and ord(
                    temp[i]) <= ord('9')):
                ans = ans + temp[i]
                i += 1
            ans = ans + " "
        else:
            while (i < l and ord(temp[i]) >= ord(
                    '*') and ord(temp[i]) <= ord('/')):
                ans = ans + temp[i]
                i += 1
            ans = ans + " "
    return ans


if __name__ == "__main__":
    s = "34FTG234+ +- *"
    l = len(s)
    print(groupCharacters(s, l))

# Expected output:
34 FTG 234 ++-*
# find the minimum number of preprocess moves required to make two strings equal | function to return the minimum number of pre - processing moves required on string a ; length of the given strings ; to store the required answer ; run a loop upto n / 2 ; to store frequency of 4 characters ; if size is 4 ; if size is 3 ; if size is 2 ; if n is odd ; 
def Preprocess(A, B):
    n = len(A)
    ans = 0
    for i in range(n // 2):
        mp = dict()
        mp[A[i]] = 1
        if A[i] == A[n - i - 1]:
            mp[A[n - i - 1]] += 1
        if B[i] in mp .keys():
            mp[B[i]] += 1
        else:
            mp[B[i]] = 1
        if B[n - i - 1] in mp .keys():
            mp[B[n - 1 - i]] += 1
        else:
            mp[B[n - 1 - i]] = 1
        sz = len(mp)
        if (sz == 4):
            ans += 2
        elif (sz == 3):
            ans += 1 + (A[i] == A[n - i - 1])
        elif (sz == 2):
            ans += mp[A[i]] != 2
    if (n % 2 == 1 and A[n // 2] != B[n // 2]):
        ans += 1
    return ans


A = "abacaba"
B = "bacabaa"
print(Preprocess(A, B))

# Expected output:
4
# check whether two strings are equivalent or not according to given condition | this function returns the least lexicogr aphical string obtained from its two halves ; base case - if string size is 1 ; divide the string into its two halves ; form least lexicographical string ; 
def leastLexiString(s):
    if (len(s) & 1 != 0):
        return s
    x = leastLexiString(s[0:int(len(s) / 2)])
    y = leastLexiString(s[int(len(s) / 2):len(s)])
    return min(x + y, y + x)


def areEquivalent(a, b):
    return (leastLexiString(a) == leastLexiString(b))


if __name__ == '__main__':
    a = "aaba"
    b = "abaa"
    if (areEquivalent(a, b)):
        print("YES")
    else:
        print("NO")
    a = "aabb"
    b = "abab"
    if (areEquivalent(a, b)):
        print("YES")
    else:
        print("NO")

# Expected output:
YES
NO
# check if a string can be converted to another string by replacing vowels and consonants | function to check if the character is vowel or not ; function that checks if a string can be converted to another string ; find length of string ; if length is not same ; iterate for every character ; if both vowel ; both are consonants ; 
def isVowel(c):
    if (c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u'):
        return True
    return False


def checkPossibility(s1, s2):
    l1 = len(s1)
    l2 = len(s2)
    if (l1 != l2):
        return False
    for i in range(l1):
        if (isVowel(s1[i]) and isVowel(s2[i])):
            continue
        elif ((isVowel(s1[i])) == False and (isVowel(s2[i]) == False)):
            continue
        else:
            return False
    return True


S1, S2 = "abcgle", "ezggli"
if (checkPossibility(S1, S2)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# generate a string consisting of characters ' a ' and ' b ' that satisfy the given conditions | function to generate and print the required string ; more ' b ' , append " bba " ; more ' a ' , append " aab " ; equal number of ' a ' and ' b ' append " ab " ; 
def generateString(A, B):
    rt = ""
    while (0 < A or 0 < B):
        if (A < B):
            if (0 < B):
                rt = rt + 'b'
                B -= 1
            if (0 < B):
                rt += 'b'
                B -= 1
            if (0 < A):
                rt += 'a'
                A -= 1
        elif (B < A):
            if (0 < A):
                rt += 'a'
                A -= 1
            if (0 < A):
                rt += 'a'
                A -= 1
            if (0 < B):
                rt += 'b'
                B -= 1
        else:
            if (0 < A):
                rt += 'a'
                A -= 1
            if (0 < B):
                rt += 'b'
                B -= 1
    print(rt)


if __name__ == "__main__":
    A = 2
    B = 6
    generateString(A, B)

# Expected output:
bbabbabb
# number of strings that satisfy the given condition | function to return the count of valid strings ; set to store indices of valid strings ; find the maximum digit for current position ; add indices of all the strings in the set that contain maximal digit ; return number of strings in the set ; 
def countStrings(n, m, s):
    ind = dict()
    for j in range(m):
        mx = 0
        str1 = s[j]
        for i in range(n):
            mx = max(mx, int(str1[i]))
        for i in range(n):
            if int(str1[i]) == mx:
                ind[i] = 1
    return len(ind)


s = ["223", "232", "112"]
m = len(s[0])
n = len(s)
print(countStrings(n, m, s))

# Expected output:
2
# lexicographically largest sub | function to return the lexicographically largest sub - sequence of s ; get the max character from the string ; use all the occurrences of the current maximum character ; repeat the steps for the remaining string ; 
def getSubSeq(s, n):
    res = ""
    cr = 0
    while (cr < n):
        mx = s[cr]
        for i in range(cr + 1, n):
            mx = max(mx, s[i])
        lst = cr
        for i in range(cr, n):
            if (s[i] == mx):
                res += s[i]
                lst = i
        cr = lst + 1
    return res


if __name__ == '__main__':
    s = "geeksforgeeks"
    n = len(s)
    print(getSubSeq(s, n))

# Expected output:
ss