giulio98/xlcost-single-prompt huggingface dataset:
# count consonants in a string ( iterative and recursive methods ) | function to check for consonant ; to handle lower case ; to check is character is consonant ; 
def isConsonant(ch):
    ch = ch .upper()
    return not (ch == 'A' or ch == 'E' or ch == 'I' or ch ==
                'O' or ch == 'U') and ord(ch) >= 65 and ord(ch) <= 90


def totalConsonants(string):
    count = 0
    for i in range(len(string)):
        if (isConsonant(string[i])):
            count += 1
    return count


string = "abc de"
print(totalConsonants(string))

# Expected output:
3
# count consonants in a string ( iterative and recursive methods ) | function to check for consonant ; to handle lower case ; to count total number of consonants from 0 to n - 1 ; 
def isConsonant(ch):
    ch = ch .upper()
    return not (ch == 'A' or ch == 'E' or ch == 'I' or ch ==
                'O' or ch == 'U') and ord(ch) >= 65 and ord(ch) <= 90


def totalConsonants(string, n):
    if n == 1:
        return isConsonant(string[0])
    return totalConsonants(string, n - 1) + isConsonant(string[n - 1])


string = "abc de"
print(totalConsonants(string, len(string)))

# Expected output:
3
# reduce hamming distance by swapping two characters | python 3 code to decrease hamming distance using swap . ; function to return the swapped indexes to get minimum hamming distance . ; find the initial hamming distance ; case - i : to decrease distance by two ; ascii values of present character . ; if two same letters appear in different positions print their indexes ; store the index of letters which is in wrong position ; case : ii ; if misplaced letter is found , print its original index and its new index ; store the index of letters in wrong position ; case - iii ; 

MAX = 26


def Swap(s, t, n):
    dp = [[-1 for x in range(MAX)]for y in range(MAX)]
    tot = 0
    for i in range(n):
        if (s[i] != t[i]):
            tot += 1
    for i in range(n):
        a = ord(s[i]) - ord('a')
        b = ord(t[i]) - ord('a')
        if (a == b):
            continue
        if (dp[a][b] != -1):
            print(i + 1, " ", dp[a][b] + 1)
            return
        dp[b][a] = i
    A = [-1] * MAX
    B = [-1] * MAX
    for i in range(n):
        a = ord(s[i]) - ord('a')
        b = ord(t[i]) - ord('a')
        if (a == b):
            continue
        if (A[b] != -1):
            print(i + 1, A[b] + 1)
            return
        if (B[a] != -1):
            print(i + 1, B[a] + 1)
            return
        A[a] = i
        B[b] = i
    print("-1")


if __name__ == "__main__":
    S = "permanent"
    T = "pergament"
    n = len(S)
    if (S == "" or T == ""):
        print("Required string is empty.")
    else:
        Swap(S, T, n)

# Expected output:
6 4
# convert string x to an anagram of string y with minimum replacements | python3 program to convert string x to string y which minimum number of changes . ; function that converts string x into lexicographically smallest anagram of string y with minimal changes ; counting frequency of characters in each string . ; we maintain two more counter arrays ctrx [ ] and ctry [ ] ctrx [ ] maintains the count of extra elements present in string x than string y ctry [ ] maintains the count of characters missing from string x which should be present in string y . ; this means that we cannot edit the current character as it 's frequency  in string x is equal to or less  than the frequency in string y.  thus, we go to the next position ; here , we try to find that character , which has more frequency in string y and less in string x . we try to find this character in lexicographical order so that we get lexicographically smaller string ; this portion deals with the lexicographical property . now , we put a character in string x when either this character has smaller value than the character present there right now or if this is the last position for it to exchange , else we fix the character already present here in this position . ; 

MAX = 26


def printAnagramAndChanges(x, y):
    x = list(x)
    y = list(y)
    countx, county = [0] * MAX, [0] * MAX
    ctrx, ctry = [0] * MAX, [0] * MAX
    change = 0
    l = len(x)
    for i in range(l):
        countx[ord(x[i]) - ord('A')] += 1
        county[ord(y[i]) - ord('A')] += 1
    for i in range(MAX):
        if countx[i] > county[i]:
            ctrx[i] += (countx[i] - county[i])
        elif countx[i] < county[i]:
            ctry[i] += (county[i] - countx[i])
        change += abs(county[i] - countx[i])
    for i in range(l):
        if ctrx[ord(x[i]) - ord('A')] == 0:
            continue
        j = 0
        for j in range(MAX):
            if ctry[j] > 0:
                break
        if countx[ord(x[i]) - ord('A')] == ctrx[ord(x[i]) -
                                                ord('A')] or ord(x[i]) - ord('A') > j:
            countx[ord(x[i]) - ord('A')] -= 1
            ctrx[ord(x[i]) - ord('A')] -= 1
            ctry[j] -= 1
            x[i] = chr(ord('A') + j)
        else:
            countx[ord(x[i]) - ord('A')] -= 1
    print("Anagram :", ''.join(x))
    print("Number of changes made :", change // 2)


if __name__ == "__main__":
    x = "CDBABC"
    y = "ADCABD"
    printAnagramAndChanges(x, y)

# Expected output:
Anagram : ADBADC
Number of changes made : 2
# count number of equal pairs in a string | python3 program to count the number of pairs ; function to count the number of equal pairs ; hash table ; traverse the string and count occurrence ; stores the answer ; traverse and check the occurrence of every character ; 

MAX = 256


def countPairs(s):
    cnt = [0 for i in range(0, MAX)]
    for i in range(len(s)):
        cnt[ord(s[i]) - 97] += 1
    ans = 0
    for i in range(0, MAX):
        ans += cnt[i] * cnt[i]
    return ans


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

# Expected output:
31
# find a string in lexicographic order which is in between given two strings | function to find the lexicographically next string ; iterate from last character ; if not ' z ' , increase by one ; if ' z ' , change it to 'a ; 
def lexNext(s, n):
    for i in range(n - 1, -1, -1):
        if s[i] != 'z':
            k = ord(s[i])
            s[i] = chr(k + 1)
            return ''.join(s)

    s[i] = 'a'


if __name__ == "__main__":
    S = "abcdeg"
    T = "abcfgh"
    n = len(S)
    S = list(S)
    res = lexNext(S, n)
    if res != T:
        print(res)
    else:
        print(-1)

# Expected output:
abcdeh
# find the arrangement of queue at given time | prints the arrangement at time = t ; checking the entire queue for every moment from time = 1 to time = t . ; if current index contains ' b ' and next index contains ' g ' then swap ; 
def solve(n, t, p):
    s = list(p)
    for i in range(0, t):
        for j in range(0, n - 1):
            if (s[j] == 'B' and s[j + 1] == 'G'):
                temp = s[j]
                s[j] = s[j + 1]
                s[j + 1] = temp
                j = j + 1
    print(''.join(s))


n = 6
t = 2
p = "BBGBBG"
solve(n, t, p)

# Expected output:
GBBGBB
# add two numbers represented by two arrays | return sum of two number represented by the arrays . size of a [ ] is greater than b [ ] . it is made sure be the wrapper function ; array to store sum . ; until we reach beginning of array . we are comparing only for second array because we have already compare the size of array in wrapper function . ; find sum of corresponding element of both array . ; finding carry for next sum . ; if second array size is less the first array size . ; add carry to first array elements . ; if there is carry on adding 0 index elements . append 1 to total sum . ; converting array into number . ; wrapper function ; making first array which have greater number of element ; 
def calSumUtil(a, b, n, m):
    sum = [0] * n
    i = n - 1
    j = m - 1
    k = n - 1
    carry = 0
    s = 0
    while j >= 0:
        s = a[i] + b[j] + carry
        sum[k] = (s % 10)
        carry = s // 10
        k -= 1
        i -= 1
        j -= 1
    while i >= 0:
        s = a[i] + carry
        sum[k] = (s % 10)
        carry = s // 10
        i -= 1
        k -= 1
    ans = 0
    if carry:
        ans = 10
    for i in range(n):
        ans += sum[i]
        ans *= 10
    return ans // 10


def calSum(a, b, n, m):
    if n >= m:
        return calSumUtil(a, b, n, m)
    else:
        return calSumUtil(b, a, m, n)


a = [9, 3, 9]
b = [6, 1]
n = len(a)
m = len(b)
print(calSum(a, b, n, m))

# Expected output:
1000
# longest common anagram subsequence | python 3 implementation to find the length of the longest common anagram subsequence ; function to find the length of the longest common anagram subsequence ; list for storing frequencies of each character ; calculate frequency of each character of 'str1[] ; calculate frequency of each character of 'str2[] ; for each character add its minimum frequency out of the two strings in 'len ; required length ; 


SIZE = 26


def longCommonAnagramSubseq(str1, str2,
                            n1, n2):
    freq1 = [0] * SIZE
    freq2 = [0] * SIZE

    l = 0
    for i in range(n1):
        freq1[ord(str1[i]) -
              ord('a')] += 1
    for i in range(n2):
        freq2[ord(str2[i]) -
              ord('a')] += 1
    for i in range(SIZE):
        l += min(freq1[i], freq2[i])
    return l


if __name__ == "__main__":

    str1 = "abdacp"
    str2 = "ckamb"
    n1 = len(str1)
    n2 = len(str2)
    print("Length = ",
          longCommonAnagramSubseq(str1, str2,
                                  n1, n2))

# Expected output:
Length =  3
# panalphabetic window in a string | return if given string contain panalphabetic window . ; traversing the string ; if character of string is equal to ch , increment ch . ; if all characters are found , return true . ; 
def isPanalphabeticWindow(s, n):
    ch = 'a'
    for i in range(0, n):
        if (s[i] == ch):
            ch = chr(ord(ch) + 1)
        if (ch == 'z'):
            return True
    return False


s = "abujm zvcd acefc deghf gijkle m n o p pafqrstuvwxyzfap"
n = len(s)
if (isPanalphabeticWindow(s, n)):
    print("YES")
else:
    print("NO")

# Expected output:
YES
# program to print characters present at prime indexes in a given string | python3 program to print characters at prime index in a given string ; corner case ; check from 2 to n - 1 ; function to print character at prime index ; loop to check if index prime or not ; 
def isPrime(n):
    if n <= 1:
        return False
    for i in range(2, n):
        if n % i == 0:
            return False
    return True


def prime_index(input):
    p = list(input)
    s = ""
    for i in range(2, len(p) + 1):
        if isPrime(i):
            s = s + input[i - 1]
    print(s)


input = "GeeksforGeeks"
prime_index(input)

# Expected output:
eesoes
# check whether a given string is heterogram or not | python3 code to check whether the given string is heterogram or not . ; traversing the string . ; ignore the space ; if already encountered ; else return false . ; 
def isHeterogram(s, n):
    hash = [0] * 26
    for i in range(n):
        if s[i] != ' ':
            if hash[ord(s[i]) - ord('a')] == 0:
                hash[ord(s[i]) - ord('a')] = 1
            else:
                return False
    return True


s = "the big dwarf only jumps"
n = len(s)
print("YES"if isHeterogram(s, n)else "NO")

# Expected output:
YES
# print given sentence into its equivalent ascii form | function to compute the ascii value of each character one by one ; 
def ASCIISentence(str):
    for i in str:
        print(ord(i), end='')
    print('',  end='')


str = "GeeksforGeeks"
print("ASCII Sentence:")
ASCIISentence(str)

# Expected output:
ASCII Sentence:
7110110110711510211111471101101107115
# snake case of a given sentence | function to replace spaces and convert into snake case ; converting space to underscor ; if not space , convert into lower character ; 
def convert(string):
    n = len(string)
    string = list(string)
    for i in range(n):
        if (string[i] == ' '):
            string[i] = '_'
        else:
            string[i] = string[i].lower()
    string = "".join(string)
    print(string)


if __name__ == "__main__":
    string = "I got intern at geeksforgeeks"
    convert(string)

# Expected output:
i_got_intern_at_geeksforgeeks
# find the size of largest subset of anagram words | utility function to find size of largest subset of anagram ; sort the string ; increment the count of string ; compute the maximum size of string ; 
def largestAnagramSet(arr, n):
    maxSize = 0
    count = {}
    for i in range(n):
        arr[i] = ''.join(sorted(arr[i]))
        if arr[i] in count:
            count[arr[i]] += 1
        else:
            count[arr[i]] = 1
        maxSize = max(maxSize, count[arr[i]])
    return maxSize


arr = ["ant", "magenta", "magnate", "tan", "gnamate"]
n = len(arr)
print(largestAnagramSet(arr, n))
arr1 = ["cars", "bikes", "arcs", "steer"]
n = len(arr1)
print(largestAnagramSet(arr1, n))

# Expected output:
3
2
# program to count vowels , consonant , digits and special characters in string . | function to count number of vowels , consonant , digits and special character in a string . ; declare the variable vowels , consonant , digit and special characters ; str . length ( ) function to count number of character in given string . ; to handle upper case letters ; 
def countCharacterType(str):
    vowels = 0
    consonant = 0
    specialChar = 0
    digit = 0
    for i in range(0, len(str)):
        ch = str[i]
        if ((ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z')):
            ch = ch .lower()
            if (ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u'):
                vowels += 1
            else:
                consonant += 1
        elif (ch >= '0' and ch <= '9'):
            digit += 1
        else:
            specialChar += 1
    print("Vowels:", vowels)
    print("Consonant:", consonant)
    print("Digit:", digit)
    print("Special Character:", specialChar)


str = "geeks for geeks121"
countCharacterType(str)

# Expected output:
Vowels: 5
Consonant: 8
Digit: 3
Special Character: 2
# next word that does not contain a palindrome and has characters from first k | function to return lexicographically next word ; we made m as m + 97 that means our required string contains not more than m + 97 ( as per ascii value ) in it . ; increment last alphabet to make next lexicographically next word . ; if i - th alphabet not in first k letters then make it as " a " and then increase ( i - 1 ) th letter ; to check whether formed string palindrome or not . ; increment i . ; if i less than or equals to one that means we not formed such word . ; 
def findNextWord(s, m):
    m += 97
    n = len(s)
    i = len(s) - 1
    s[i] = chr(ord(s[i]) + 1)
    while i >= 0 and i <= n - 1:
        if ord(s[i]) >= m:
            s[i] = 'a'
            i -= 1
            s[i] = chr(ord(s[i]) + 1)
        elif s[i] == s[i - 1] or s[i] == s[i - 2]:
            s[i] = chr(ord(s[i]) + 1)
        else:
            i += 1
    if i <= -1:
        print("-1")
    else:
        print(''.join(s))


if __name__ == "__main__":
    string = "abcd"
    k = 4
    findNextWord(list(string), k)

# Expected output:
abda
# replace a character c1 with c2 and c2 with c1 in a string s | python3 program to replace c1 with c2 and c2 with c1 ; loop to traverse in the string ; check for c1 and replace ; check for c2 and replace ; 
def replace(s, c1, c2):
    l = len(s)
    for i in range(l):
        if (s[i] == c1):
            s = s[0:i] + c2 + s[i + 1:]
        elif (s[i] == c2):
            s = s[0:i] + c1 + s[i + 1:]
    return s


if __name__ == '__main__':
    s = "grrksfoegrrks"
    c1 = 'e'
    c2 = 'r'
    print(replace(s, c1, c2))

# Expected output:
geeksforgeeks
# fibonacci word | returns n - th fibonacci word ; 
def fibWord(n):
    Sn_1 = "0"
    Sn = "01"
    tmp = ""
    for i in range(2, n + 1):
        tmp = Sn
        Sn += Sn_1
        Sn_1 = tmp
    return Sn


n = 6
print(fibWord(n))

# Expected output:
010010100100101001010
# change string to a new character set | function for converting the string ; find the index of each element of the string in the modified set of alphabets replace the element with the one having the same index in the actual set of alphabets ; 
def conversion(charSet, str1):
    s2 = ""
    for i in str1:
        s2 += alphabets[charSet .index(i)]
    return s2


if __name__ == '__main__':
    alphabets = "abcdefghijklmnopqrstuvwxyz"
    charSet = "qwertyuiopasdfghjklzxcvbnm"
    str1 = "egrt"
    print(conversion(charSet, str1))

# Expected output:
code
# different substrings in a string that start and end with given strings | function to return number of different sub - strings ; initially our answer is zero . ; find the length of given strings ; currently make array and initially put zero . ; find occurrence of " a " and " b " in string " s " ; we use a hash to make sure that same substring is not counted twice . ; go through all the positions to find occurrence of " a " first . ; if we found occurrence of " a " . ; then go through all the positions to find occurrence of " b " . ; if we do found " b " at index j then add it to already existed substring . ; if we found occurrence of " b " . ; now add string " b " to already existed substring . ; if current substring is not included already . ; put any non negative integer to make this string as already existed . ; make substring null . ; return answer . ; 
def numberOfDifferentSubstrings(s, a, b):
    ans = 0
    ls = len(s)
    la = len(a)
    lb = len(b)
    x = [0] * ls
    y = [0] * ls
    for i in range(ls):
        if (s[i:la + i] == a):
            x[i] = 1
        if (s[i:lb + i] == b):
            y[i] = 1
    hash = []
    curr_substr = ""
    for i in range(ls):
        if (x[i]):
            for j in range(i, ls):
                if (not y[j]):
                    curr_substr += s[j]
                if (y[j]):
                    curr_substr += s[j:lb + j]
                    if curr_substr not in hash:
                        ans += 1
                    hash .append(curr_substr)
            curr_substr = ""
    return ans


if __name__ == "__main__":
    s = "codecppforfood"
    begin = "c"
    end = "d"
    print(numberOfDifferentSubstrings(s, begin, end))

# Expected output:
3
# printing string in plus ‘ + ’ pattern in the matrix | python 3 program to print the string in ' plus ' pattern ; function to make a cross in the matrix ; as , it is not possible to make the cross exactly in the middle of the matrix with an even length string . ; declaring a 2d array i . e a matrix ; now , we will fill all the elements of the array with 'x ; now , we will place the characters of the string in the matrix , such that a cross is formed in it . ; here the characters of the string will be added in the middle column of our array . ; here the characters of the string will be added in the middle row of our array . ; now finally , we will print the array ; 

max = 100


def carveCross(str):
    n = len(str)
    if (n % 2 == 0):
        print("Not possible. Please enter ", "oddlengthstring.")
    else:
        arr = [[False for x in range(max)]for y in range(max)]
        m = n // 2
        for i in range(n):
            for j in range(n):
                arr[i][j] = 'X'
        for i in range(n):
            arr[i][m] = str[i]
        for i in range(n):
            arr[m][i] = str[i]
        for i in range(n):
            for j in range(n):
                print(arr[i][j], end=" ")
            print()


if __name__ == "__main__":
    str = "PICTURE"
    carveCross(str)

# Expected output:
X X X P X X X 
X X X I X X X 
X X X C X X X 
P I C T U R E 
X X X U X X X 
X X X R X X X 
X X X E X X X
# binary string of given length that without a palindrome of size 3 | python3 program find a binary string of given length that doesn 't contain a palindrome of size 3. ; printing the character according to i ; 
def generateString(n):
    s = ""
    for i in range(n):
        if ((i & 2) > 1):
            s += 'b'
        else:
            s += 'a'
    print(s)


if __name__ == '__main__':
    n = 5
    generateString(n)
    n = 8
    generateString(n)
    n = 10
    generateString(n)

# Expected output:
aabba
aabbaabb
aabbaabbaa
# print all subsequences of a string | iterative method | function to find subsequence ; check if jth bit in binary is 1 ; if jth bit is 1 , include it in subsequence ; function to print all subsequences ; map to store subsequence lexicographically by length ; total number of non - empty subsequence in string is 2 ^ len - 1 ; i = 0 , corresponds to empty subsequence ; subsequence for binary pattern i ; storing sub in map ; it . first is length of subsequence it . second is set < string > ; ii is iterator of type set < string > ; 
def subsequence(s, binary, length):
    sub = ""
    for j in range(length):
        if (binary & (1 << j)):
            sub += s[j]
    return sub


def possibleSubsequences(s):
    sorted_subsequence = {}
    length = len(s)
    limit = 2 ** length
    for i in range(1, limit):
        sub = subsequence(s, i, length)
        if len(sub) in sorted_subsequence .keys():
            sorted_subsequence[len(sub)] = tuple(
                list(sorted_subsequence[len(sub)]) + [sub])
        else:
            sorted_subsequence[len(sub)] = [sub]
    for it in sorted_subsequence:
        print("Subsequences of length =", it, "are:")
        for ii in sorted(set(sorted_subsequence[it])):
            print(ii, end=' ')
        print()


s = "aabc"
possibleSubsequences(s)

# Expected output:
Subsequences of length = 1 are:
a b c 
Subsequences of length = 2 are:
aa ab ac bc 
Subsequences of length = 3 are:
aab aac abc 
Subsequences of length = 4 are:
aabc
# print all subsequences of a string | iterative method | python3 program to print all subsequences of a string in an iterative manner ; function to find subsequence ; loop while binary is greater than ; get the position of rightmost set bit ; append at beginning as we are going from lsb to msb ; resets bit at pos in binary ; function to print all subsequences ; map to store subsequence lexicographically by length ; total number of non - empty subsequence in string is 2 ^ len - 1 ; i = 0 , corresponds to empty subsequence ; subsequence for binary pattern i ; storing sub in map ; it . first is length of subsequence it . second is set < string > ; ii is iterator of type set < string > ; 

from math import log2, floor


def subsequence(s, binary):
    sub = ""
    while (binary > 0):
        pos = floor(log2(binary & -binary) + 1)
        sub = s[pos - 1] + sub
        binary = (binary & ~(1 << (pos - 1)))
    sub = sub[::-1]
    return sub


def possibleSubsequences(s):
    sorted_subsequence = {}
    length = len(s)
    limit = 2 ** length
    for i in range(1, limit):
        sub = subsequence(s, i)
        if len(sub) in sorted_subsequence .keys():
            sorted_subsequence[len(sub)] = tuple(
                list(sorted_subsequence[len(sub)]) + [sub])
        else:
            sorted_subsequence[len(sub)] = [sub]
    for it in sorted_subsequence:
        print("Subsequences of length =", it, "are:")
        for ii in sorted(set(sorted_subsequence[it])):
            print(ii, end=' ')
        print()


s = "aabc"
possibleSubsequences(s)

# Expected output:
Subsequences of length = 1 are:
a b c 
Subsequences of length = 2 are:
aa ab ac bc 
Subsequences of length = 3 are:
aab aac abc 
Subsequences of length = 4 are:
aabc
# program to find remainder when large number is divided by 11 | function to return remainder ; len is variable to store the length of number string . ; loop that find remainder ; 
def remainder(st):
    ln = len(st)
    rem = 0
    for i in range(0, ln):
        num = rem * 10 + (int)(st[i])
        rem = num % 11
    return rem


st = "3435346456547566345436457867978"
print(remainder(st))

# Expected output:
4