giulio98/xlcost-single-prompt huggingface dataset:
# find value after n operations to remove n characters of string s with given constraints | function to find the value after n operations to remove all the n characters of string s ; iterate till n ; remove character at ind and decrease n ( size of string ) ; increase count by ind + 1 ; 
def charactersCount(str, n):
    count = 0
    while (n > 0):
        cur = str[0]
        ind = 0
        for j in range(1, n):
            if (str[j] < cur):
                cur = str[j]
                ind = j
        str = str[0:ind] + str[ind + 1:]
        n -= 1
        count += ind + 1
    print(count)


if __name__ == '__main__':
    str = "aabbc"
    n = 5
    charactersCount(str, n)

# Expected output:
5
# print the middle character of a string | function that prints the middle character of a string ; finding string length ; finding middle index of string ; prthe middle character of the string ; 
def printMiddleCharacter(str):
    length = len(str)
    middle = length // 2
    print(str[middle])


str = "GeeksForGeeks"
printMiddleCharacter(str)

# Expected output:
o
# maximize length of the string by concatenating characters from an array of strings | function to check if all the string characters are unique ; check for repetition in characters ; function to generate all possible strings from the given array ; base case ; consider every string as a starting substring and store the generated string ; add current string to result of other strings and check if characters are unique or not ; function to find the maximum possible length of a string ; return max length possible ; return the answer ; 
def check(s):
    a = set()
    for i in s:
        if i in a:
            return False
        a .add(i)
    return True


def helper(arr, ind):
    if (ind == len(arr)):
        return [""]
    tmp = helper(arr, ind + 1)
    ret = tmp
    for i in tmp:
        test = i + arr[ind]
        if (check(test)):
            ret .append(test)
    return ret


def maxLength(arr):
    tmp = helper(arr, 0)
    l = 0
    for i in tmp:
        l = l if l > len(i)else len(i)
    return l


if __name__ == '__main__':
    s = []
    s .append("abcdefgh")
    print(maxLength(s))

# Expected output:
8
# perform range sum queries on string as per given condition | function to perform range sum queries on string as per the given condition ; initialize n by string size ; create array a [ ] for prefix sum ; iterate till n ; traverse the queries ; check if if l == 1 range sum will be a [ r - 1 ] ; condition if l > 1 range sum will be a [ r - 1 ] - a [ l - 2 ] ; given string ; 
def Range_sum_query(S, Query):
    N = len(S)
    A = [0] * N
    A[0] = ord(S[0]) - ord('a') + 1
    for i in range(1, N):
        A[i] = ord(S[i]) - ord('a') + 1
        A[i] = A[i] + A[i - 1]
    for i in range(len(Query)):
        if (Query[i][0] == 1):
            print(A[Query[i][1] - 1])
        else:
            print(A[Query[i][1] - 1] - A[Query[i][0] - 2])


S = "abcd"
Query = []
Query .append([2, 4])
Query .append([1, 3])
Range_sum_query(S, Query)

# Expected output:
9
6
# generate all possible permutations of a number divisible by n | function to generate all permutations and print the ones that are divisible by the n ; convert string to integer ; check for divisibility and print it ; print all the permutations ; swap characters ; permute remaining characters ; revoke the swaps ; 
def permute(st, l, r, n):
    if (l == r):
        p = ''.join(st)
        j = int(p)
        if (j % n == 0):
            print(p)
        return
    for i in range(l, r):
        st[l], st[i] = st[i], st[l]
        permute(st, l + 1, r, n)
        st[l], st[i] = st[i], st[l]

if __name__ == "__main__":
    st = "125"
    n = 5
    length = len(st)
    if (length > 0):
        p = list(st)
    permute(p, 0, length, n)

# Expected output:
125
215
# check if binary representations of 0 to n are present as substrings in given binary string | function to convert decimal to binary representation ; iterate over all bits of n ; if bit is 1 ; return binary representation ; function to check if binary conversion of numbers from n to 1 exists in the string as a substring or not ; to store the count of number exists as a substring ; traverse from n to 1 ; if current number is not present in map ; store current number ; find binary of t ; if the string s is a substring of str ; mark t as true ; increment the count ; update for t / 2 ; special judgment '0 ; if the count is n + 1 , return " yes " ; 
def decimalToBinary(N):
    ans = ""
    while (N > 0):
        if (N & 1):
            ans = '1' + ans
        else:
            ans = '0' + ans
        N //= 2
    return ans


def checkBinaryString(str, N):
    map = [0] * (N + 10)
    cnt = 0
    for i in range(N, -1, -1):
        if (not map[i]):
            t = i
            s = decimalToBinary(t)
            if (s in str):
                while (t and not map[t]):
                    map[t] = 1
                    cnt += 1
                    t >>= 1
    for i in range(len(str)):
        if (str[i] == '0'):
            cnt += 1
            break
    if (cnt == N+1):
        return "True"
    else:
        return "False"


if __name__ == '__main__':
    str = "0110"
    N = 3
    print(checkBinaryString(str, N))

# Expected output:
True
# find the word with most anagrams in a given sentence | function to find the word with maximum number of anagrams ; primes assigned to 26 alphabets ; stores the product and word mappings ; stores the frequencies of products ; calculate the product of primes assigned ; if product already exists ; otherwise ; fetch the most frequent product ; return a string with that product ; 
def largestAnagramGrp(arr):
    prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
             43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
    max = -1
    maxpdt = -1
    W = {}
    P = {}
    for temp in arr:
        c = [i for i in temp]
        pdt = 1
        for t in c:
            pdt *= prime[ord(t) - ord('a')]
        if (pdt in P):
            P[pdt] = P .get(pdt, 0) + 1
        else:
            W[pdt] = temp
            P[pdt] = 1
    for e in P:
        if (max < P[e]):
            max = P[e]
            maxpdt = e
    return W[maxpdt]


if __name__ == '__main__':
    S = "please be silent and listen to what the professor says"
    arr = S .split(" ")
    print(largestAnagramGrp(arr))

# Expected output:
silent
# replace every vowels with lexicographically next vowel in a string | function to replace every vowel with next vowel lexicographically ; storing the vowels in the map with custom numbers showing their index ; iterate over the string ; if the current character is a vowel find the index in hash and replace it with next vowel from hash ; 
def print_next_vovel_string(st):
    m = {}
    m['a'] = 0
    m['e'] = 1
    m['i'] = 2
    m['o'] = 3
    m['u'] = 4
    arr = ['a', 'e', 'i', 'o', 'u']
    N = len(st)
    for i in range(N):
        c = st[i]
        if (c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u'):
            index = m[st[i]] + 1
            newindex = index % 5
            st = st .replace(st[i], arr[newindex], 1)
    return st


if __name__ == "__main__":
    st = "geeksforgeeks"
    print(print_next_vovel_string(st))

# Expected output:
giiksfurgiiks
# check if string is palindrome after removing all consecutive duplicates | function to check if a string is palindrome or not ; length of the string ; check if its a palindrome ; if the palindromic condition is not met ; return true as str is palindromic ; function to check if string str is palindromic after removing every consecutive characters from the str ; length of the string str ; create an empty compressed string ; the first character will always be included in final string ; check all the characters of the string ; if the current character is not same as its previous one , then insert it in the final string ; check if the compressed string is a palindrome ; 
def isPalindrome(Str):
    Len = len(Str)
    for i in range(Len):
        if (Str[i] != Str[Len - i - 1]):
            return False
    return True


def isCompressablePalindrome(Str):
    Len = len(Str)
    compressed = ""
    compressed += Str[0]
    for i in range(1, Len):
        if (Str[i] != Str[i - 1]):
            compressed += Str[i]
    return isPalindrome(compressed)


if __name__ == '__main__':
    Str = "abbcbbbaaa"
    if (isCompressablePalindrome(Str)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# count of substrings consisting only of vowels | function to check vowel or not ; function to count all substrings in a string which contains only vowels ; if current character is vowel ; increment ; count all possible substring of calculated length ; reset the length ; add remaining possible substrings consisting of vowels occupying last indices of the string ; 
def isvowel(ch):
    return (ch in "aeiou")


def CountTotal(s):
    ans = 0
    n = len(s)
    cnt = 0
    for i in range(0, n):
        if (isvowel(s[i])):
            cnt += 1
        else:
            ans += (cnt * (cnt + 1) // 2)
            cnt = 0
    if (cnt != 0):
        ans += (cnt * (cnt + 1) // 2)
    return ans


s = "geeksforgeeks"
print(CountTotal(s))

# Expected output:
7
# number formed by flipping all bits to the left of rightmost set bit | function to get the total count ; moving until we get the rightmost set bit ; to get total number of bits in a number ; function to find the integer formed after flipping all bits to the left of the rightmost set bit ; find the total count of bits and the rightmost set bit ; xor given number with the number which has is made up of only totbits set ; to avoid flipping the bits to the right of the set bit , take xor with the number made up of only set firstbits ; 
def getTotCount(num):
    totCount = 1
    firstCount = 1
    temp = 1
    while (not (num & temp)):
        temp = temp << 1
        totCount += 1
    firstCount = totCount
    temp = num >> totCount
    while (temp):
        totCount += 1
        temp = temp >> 1
    return totCount, firstCount


def flipBitsFromRightMostSetBit(num):
    totbit, firstbit = getTotCount(num)
    num1 = num ^ ((1 << totbit) - 1)
    num1 = num1 ^ ((1 << firstbit) - 1)
    return num1


if __name__ == '__main__':
    n = 120
    print(flipBitsFromRightMostSetBit(n))

# Expected output:
8
# longest substring of vowels with no two adjacent alphabets same | function to check a character is vowel or not ; function to find length of longest substring consisting only of vowels and no similar adjacent alphabets ; stores max length of valid substring ; stores length of current valid substring ; if curr and prev character are not same , include it ; if same as prev one , start new substring from here ; store max in maxlen ; 
def isVowel(x):
    return (x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u')


def findMaxLen(s):
    maxLen = 0
    cur = 0
    if (isVowel(s[0])):
        maxLen = 1
    cur = maxLen
    for i in range(1, len(s)):
        if (isVowel(s[i])):
            if (s[i] != s[i - 1]):
                cur += 1
            else:
                cur = 1
        else:
            cur = 0
        maxLen = max(cur, maxLen)
    return maxLen


Str = "aeoibsddaeiouudb"
print(findMaxLen(Str))

# Expected output:
5
# count of non | iterative function to calculate base ^ pow in o ( log y ) ; function to return the count of non palindromic strings ; count of strings using n characters with repetitions allowed ; count of palindromic strings ; count of non - palindromic strings ; 
def power(base, pwr):
    res = 1
    while (pwr > 0):
        if (pwr & 1):
            res = res * base
        base = base * base
        pwr >>= 1
    return res


def countNonPalindromicString(n, m):
    total = power(n, m)
    palindrome = power(n, m // 2 + m % 2)
    count = total - palindrome
    return count


if __name__ == '__main__':
    n = 3
    m = 5
    print(countNonPalindromicString(n, m))

# Expected output:
216
# count of k | to store the frequency array ; function to check palindromic of of any substring using frequency array ; initialise the odd count ; traversing frequency array to compute the count of characters having odd frequency ; returns true if odd count is atmost 1 ; function to count the total number substring whose any permutations are palindromic ; computing the frequency of first k character of the string ; to store the count of palindromic permutations ; checking for the current window if it has any palindromic permutation ; start and end poof window ; decrementing count of first element of the window ; incrementing count of next element of the window ; checking current window character frequency count ; return the final count ; 

freq = [0] * 26


def checkPalindrome():
    oddCnt = 0
    for x in freq:
        if (x % 2 == 1):
            oddCnt += 1
    return oddCnt <= 1


def countPalindromePermutation(s, k):
    for i in range(k):
        freq[ord(s[i]) - 97] += 1
    ans = 0
    if (checkPalindrome()):
        ans += 1
    i = 0
    j = k
    while (j < len(s)):
        freq[ord(s[i]) - 97] -= 1
        i += 1
        freq[ord(s[j]) - 97] += 1
        j += 1
        if (checkPalindrome()):
            ans += 1
    return ans


str = "abbaca"
K = 3
print(countPalindromePermutation(str, K))

# Expected output:
3
# minimum flips required to form given binary string where every flip changes all bits to its right as well | function to return the count of minimum flips required ; if curr occurs in the final string ; switch curr to '0' if '1' or vice - versa ; 
def minFlips(target):
    curr = '1'
    count = 0
    for i in range(len(target)):
        if (target[i] == curr):
            count += 1
            curr = chr(48 + (ord(curr) + 1) % 2)
    return count


if __name__ == "__main__":
    S = "011000"
    print(minFlips(S))

# Expected output:
2
# check if a number ends with another number or not | python3 program for the above approach ; function to check if b is a suffix of a or not ; find the number of digit in b ; subtract b from a ; returns true , if b is a suffix of a ; 

import math


def checkSuffix(A, B):
    digit_B = int(math .log10(B)) + 1
    A -= B
    return (A % int(math .pow(10, digit_B)))


A = 12345
B = 45
result = checkSuffix(A, B)
if (result == 0):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# minimum length of substring whose rotation generates a palindromic substring | python3 program to find the minimum length of substring whose rotation generates a palindromic substring ; function to return the minimum length of substring ; store the index of previous occurrence of the character ; variable to store the maximum length of substring ; if the current character hasn 't appeared yet ; if the character has occured within one or two previous index , a palindromic substring already exists ; update the maximum ; replace the previous index of the character by the current index ; if character appeared at least twice ; 

import sys
INT_MAX = sys .maxsize


def count_min_length(s):
    hash = [0] * 26
    ans = sys .maxsize
    for i in range(26):
        hash[i] = -1
    for i in range(len(s)):
        if (hash[ord(s[i]) - ord('a')] == -1):
            hash[ord(s[i]) - ord('a')] = i
        else:
            if (hash[ord(s[i]) - ord('a')] == i -
                    1 or hash[ord(s[i]) - ord('a')] == i - 2):
                return 0
            ans = min(ans, i - hash[ord(s[i]) - ord('a')] - 1)
            hash[ord(s[i]) - ord('a')] = i
    if (ans == INT_MAX):
        return -1
    return ans


if __name__ == "__main__":
    string = "abcdeba"
    print(count_min_length(string))

# Expected output:
3
# program to remove html tags from a given string | python3 program for the above approach ; function to remove the html tags from the given tags ; print string after removing tags ; 


import re


def RemoveHTMLTags(strr):
    print(re .compile('<[^>]+>').sub('', strr))


if __name__ == '__main__':
    strr = "<div><b>Geeks for Geeks</b></div>"
    RemoveHTMLTags(strr)

# Expected output:
Geeks for Geeks
# score of parentheses using tree | customized tree class or struct , contains all required methods . ; function to add a child into the list of children ; function to change the parent pointer to the node passed ; function to return the parent of the current node ; function to compute the score recursively . ; base case ; adds scores of all children ; function to create the tree structure ; creating a node for every " ( ) " ; if we find " ( " we add a node as a child ; on finding " ) " which confirms that a pair is closed , we go back to the parent ; 

class TreeNode:
    def __init__(self):
        self .parent = None
        self .children = []

    def addChild(self, node):
        self .children .append(node)

    def setParent(self, node):
        self .parent = node

    def getParent(self):
        return self .parent

    def computeScore(self):
        if (len(self .children) == 0):
            return 1
        res = 0
        for curr in self .children:
            res += curr .computeScore()
        if (self .parent is None):
            return res
        else:
            return 2 * res


def computeTree(s):
    current = TreeNode()
    root = current
    for i in range(len(s)):
        if (s[i] == '('):
            child = TreeNode()
            child .setParent(current)
            current .addChild(child)
            current = child
        else:
            current = current .getParent()
    return root


if __name__ == '__main__':
    s = "(()(()))"
    root = computeTree(s)
    print(root .computeScore())

# Expected output:
6
# move all occurrence of letter ' x ' from the string s to the end using recursion | recursive program to bring ' x ' to the end ; when the string is completed from reverse direction end of recursion ; if the character x is found ; transverse the whole string ; swap the x so that it moves to the last ; call to the smaller problem now ; 
def rec(a, i):
    if (i == 0):
        a.pop()
        print("".join(a))
        return
    if (a[i] == 'x'):
        j = i
        while (a[j] != '' and a[j + 1] != ''):
            (a[j], a[j + 1]) = (a[j + 1], a[j])
            j += 1
    rec(a, i - 1)


if __name__ == "__main__":

    a = ['g', 'e', 'e', 'k', 'x',
         's', 'x', 'x', 'k', 's', '']
    n = 10
    rec(a, n - 1)

# Expected output:
geeksksxxx
# find the largest alphabetic character present in the string | function to find the largest alphabetic character ; array for keeping track of both uppercase and lowercase english alphabets ; iterate from right side of array to get the largest index character ; check for the character if both its uppercase and lowercase exist or not ; return - 1 if no such character whose uppercase and lowercase present in string str ; 
def largestCharacter(str):
    uppercase = [False] * 26
    lowercase = [False] * 26
    arr = list(str)
    for c in arr:
        if (c .islower()):
            lowercase[ord(c) - ord('a')] = True
        if (c .isupper()):
            uppercase[ord(c) - ord('A')] = True
    for i in range(25, -1, -1):
        if (uppercase[i] and lowercase[i]):
            return chr(i + ord('A')) + ""
    return "-1"


str = "admeDCAB"
print(largestCharacter(str))

# Expected output:
D
# print string after removing all ( “ 10 ” or “ 01 ” ) from the binary string | function to print the final string after removing all the occurrences of "10" and "01" from the given binary string ; variables to store the count of 1 ' s ▁ and ▁ 0' s ; length of the string ; for loop to count the occurrences of 1 ' s ▁ and ▁ 0' s in the string ; to check if the count of 1 ' s ▁ is ▁ ▁ greater ▁ than ▁ the ▁ count ▁ of ▁ 0' s or not . if x is greater , then those many 1 's  are printed. ; length of the final remaining string after removing all the occurrences ; printing the final string ; 
def finalString(st):
    x, y = 0, 0
    n = len(st)
    for i in range(n):
        if (st[i] == '1'):
            x += 1
        else:
            y += 1
    if (x > y):
        left = 1
    else:
        left = 0
    length = n - 2 * min(x, y)
    for i in range(length):
        print(left, end="")


if __name__ == "__main__":
    st = "010110100100000"
    finalString(st)

# Expected output:
00000
# longest palindrome formed by concatenating and reordering strings of equal length | function to print the longest palindrome ; printing every string in left vector ; printing the palindromic string in the middle ; printing the reverse of the right vector to make the final output palindromic ; function to find and print the longest palindrome that can be formed ; inserting each string in the set ; vectors to add the strings in the left and right side ; to add the already present palindrome string in the middle of the solution ; iterating through all the given strings ; if the string is a palindrome it is added in the middle ; checking if the reverse of the string is already present in the set ; 
def printPalindrome(left, mid, right):
    for x in left:
        print(x, end="")
    print(mid, end="")
    right = right[::-1]
    for x in right:
        print(x, end="")
    print('', end="")


def findPalindrome(S, N, M):
    d = set()
    for i in range(M):
        d .add(S[i])
    left = []
    right = []
    mid = ""
    for i in range(N):
        t = S[i]
        t = t[::-1]
        if (t == S[i]):
            mid = t
        elif (t in d):
            left .append(S[i])
            right .append(t)
            d .remove(S[i])
            d .remove(t)
    printPalindrome(left, mid, right)


if __name__ == '__main__':
    S = ["tab", "one", "bat"]
    M = 3
    N = len(S)
    findPalindrome(S, N, M)

# Expected output:
tabbat
# lexicographically smaller string by swapping at most one character pair | function that finds whether is it possible to make string a lexicographically smaller than string b ; condition if string a is already smaller than b ; sorting temp string ; condition for first changed character of string a and temp ; condition if string a is already sorted ; finding first changed character from last of string a ; swap the two characters ; condition if string a is smaller than b ; 
def IsLexicographicallySmaller(A, B):
    if (A < B):
        return True
    temp = A
    temp = ''.join(sorted(temp))
    index = -1
    for i in range(len(A)):
        if (A[i] != temp[i]):
            index = i
            break
    if (index == -1):
        return False
    j = 0
    for i in range(len(A)):
        if (A[i] == temp[index]):
            j = i
    A = list(A)
    A[index], A[j] = A[j], A[index]
    A = ''.join(A)
    if (A < B):
        return True
    else:
        return False


A = "AGAIN"
B = "ACTION"
if (IsLexicographicallySmaller(A, B)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes