giulio98/xlcost-single-prompt huggingface dataset:
# given two strings check which string makes a palindrome first | given two strings , check which string makes palindrome first . ; returns winner of two strings ; count frequencies of characters in both given strings ; check if there is a character that appears more than once in a and does not appear in b ; 

MAX_CHAR = 26


def stringPalindrome(A, B):
    countA = [0] * MAX_CHAR
    countB = [0] * MAX_CHAR
    l1 = len(A)
    l2 = len(B)
    for i in range(l1):
        countA[ord(A[i]) - ord('a')] += 1
    for i in range(l2):
        countB[ord(B[i]) - ord('a')] += 1
    for i in range(26):
        if ((countA[i] > 1 and countB[i] == 0)):
            return 'A'
    return 'B'


if __name__ == '__main__':
    a = "abcdea"
    b = "bcdesg"
    print(stringPalindrome(a, b))

# Expected output:
A
# print the longest common substring | function to find and print the longest common substring of x [ 0. . m - 1 ] and y [ 0. . n - 1 ] ; create a table to store lengths of longest common suffixes of substrings . note that lcsuff [ i ] [ j ] contains length of longest common suffix of x [ 0. . i - 1 ] and y [ 0. . j - 1 ] . the first row and first column entries have no logical meaning , they are used only for simplicity of program ; to store length of the longest common substring ; to store the index of the cell which contains the maximum value . this cell 's index helps in building  up the longest common substring  from right to left. ; following steps build lcsuff [ m + 1 ] [ n + 1 ] in bottom up fashion . ; if true , then no common substring exists ; allocate space for the longest common substring ; traverse up diagonally form the ( row , col ) cell until lcsuff [ row ] [ col ] != 0 ; move diagonally up to previous cell ; required longest common substring ; 
def printLCSSubStr(X: str, Y: str, m: int, n: int):
    LCSuff = [[0 for i in range(n + 1)]for j in range(m + 1)]
    length = 0
    row, col = 0, 0
    for i in range(m + 1):
        for j in range(n + 1):
            if i == 0 or j == 0:
                LCSuff[i][j] = 0
            elif X[i - 1] == Y[j - 1]:
                LCSuff[i][j] = LCSuff[i - 1][j - 1] + 1
                if length < LCSuff[i][j]:
                    length = LCSuff[i][j]
                    row = i
                    col = j
            else:
                LCSuff[i][j] = 0
    if length == 0:
        print("No Common Substring")
        return
    resultStr = ['0'] * length
    while LCSuff[row][col] != 0:
        length -= 1
        row -= 1
        col -= 1
    print(''.join(resultStr))


if __name__ == "__main__":
    X = "OldSite:GeeksforGeeks.org"
    Y = "NewSite:GeeksQuiz.com"
    m = len(X)
    n = len(Y)
    printLCSSubStr(X, Y, m, n)

# Expected output:
0000000000
# convert all substrings of length ' k ' from base ' b ' to decimal | simple python3 program to convert all substrings from decimal to given base . ; saving substring in sub ; evaluating decimal for current substring and printing it . ; 

import math


def substringConversions(s, k, b):
    l = len(s)
    for i in range(l):
        if ((i + k) < l + 1):
            sub = s[i:i + k]
            sum, counter = 0, 0
            for i in range(len(sub) - 1, -1, -1):
                sum = sum + ((ord(sub[i]) - ord('0')) * pow(b, counter))
                counter += 1
            print(sum, end=" ")


s = "12212"
b, k = 3, 3
substringConversions(s, b, k)

# Expected output:
17 25 23
# longest possible chunked palindrome | here curr_str is the string whose lcp is needed leng is length of string evaluated till now and s is original string ; if there is nothing at all ! ! ; if a single letter is left out ; for each length of substring chunk in string ; if left side chunk and right side chunk are same ; call lcp for the part between the chunks and add 2 to the result . length of string evaluated till now is increased by ( i + 1 ) * 2 ; wrapper over lpcrec ( ) ; 
def LPCRec(curr_str, count, leng, s):
    if not curr_str:
        return 0
    if len(curr_str) <= 1:
        if count != 0 and len(s) - leng <= 1:
            return (count + 1)
        else:
            return 1
    n = len(curr_str)
    for i in range(n // 2):
        if (curr_str[0:i + 1] == curr_str[n - 1 - i:n]):
            return LPCRec(curr_str[i + 1:n - 1 - i],
                          count + 2, leng + (i + 1) * 2, s)
    return count + 1


def LPC(s):
    return LPCRec(s, 0, 0, s)


print("V :", LPC("V"))
print("VOLVO :", LPC("VOLVO"))
print("VOLVOV :", LPC("VOLVOV"))
print("ghiabcdefhelloadamhelloabcdefghi :",
      LPC("ghiabcdefhelloadamhelloabcdefghi"))
print("ghiabcdefhelloadamhelloabcdefghik :",
      LPC("ghiabcdefhelloadamhelloabcdefghik"))
print("antaprezatepzapreanta :", LPC("antaprezatepzapreanta"))

# Expected output:
V : 1
VOLVO : 3
VOLVOV : 5
ghiabcdefhelloadamhelloabcdefghi : 7
ghiabcdefhelloadamhelloabcdefghik : 1
antaprezatepzapreanta : 11
# find numbers of balancing positions in string | python3 program to find number of balancing points in string ; function to return number of balancing points ; hash array for storing hash of string initialized by 0 being global ; process string initially for rightvisited ; check for balancing points ; for every position inc left hash & dec rightvisited ; check whether both hash have same character or not ; either both leftvisited [ j ] and rightvisited [ j ] should have none zero value or both should have zero value ; if both have same character increment count ; 

MAX_CHAR = 256


def countBalance(string):
    n = len(string)
    leftVisited = [0] * (MAX_CHAR)
    rightVisited = [0] * (MAX_CHAR)
    for i in range(0, n):
        rightVisited[ord(string[i])] += 1
    res = 0
    for i in range(0, n):
        leftVisited[ord(string[i])] += 1
        rightVisited[ord(string[i])] -= 1
        j = 0
        while j < MAX_CHAR:
            if ((leftVisited[j] == 0 and rightVisited[j] != 0) or (
                    leftVisited[j] != 0 and rightVisited[j] == 0)):
                break
            j += 1
        if j == MAX_CHAR:
            res += 1
    return res


if __name__ == "__main__":
    string = "abaababa"
    print(countBalance(string))

# Expected output:
5
# min flips of continuous characters to make all characters same in a string | to find min number of flips in binary string ; if last character is not equal to str [ i ] increase res ; to return min flips ; 
def findFlips(str, n):
    last = ' '
    res = 0
    for i in range(n):
        if (last != str[i]):
            res += 1
        last = str[i]
    return res // 2


if __name__ == "__main__":
    str = "00011110001110"
    n = len(str)
    print(findFlips(str, n))

# Expected output:
2
# maximum length substring having all same characters after k changes | function to find the maximum length of substring having character ch ; traverse the whole string ; if character is not same as ch increase count ; while count > k traverse the string again until count becomes less than k and decrease the count when characters are not same ; length of substring will be rightindex - leftindex + 1. compare this with the maximum length and return maximum length ; function which returns maximum length of substring ; 
def findLen(A, n, k, ch):
    maxlen = 1
    cnt = 0
    l = 0
    r = 0
    while r < n:
        if A[r] != ch:
            cnt += 1
        while cnt > k:
            if A[l] != ch:
                cnt -= 1
            l += 1
        maxlen = max(maxlen, r - l + 1)
        r += 1
    return maxlen


def answer(A, n, k):
    maxlen = 1
    for i in range(26):
        maxlen = max(maxlen, findLen(A, n, k, chr(i + ord('A'))))
        maxlen = max(maxlen, findLen(A, n, k, chr(i + ord('a'))))
    return maxlen


if __name__ == "__main__":
    n = 5
    k = 2
    A = "ABABA"
    print("Maximum length =", answer(A, n, k))
    n = 6
    k = 4
    B = "HHHHHH"
    print("Maximum length =", answer(B, n, k))

# Expected output:
Maximum length = 5
Maximum length = 6
# given a sequence of words , print all anagrams together using stl | python3 program for finding all anagram pairs in the given array ; utility function for printing anagram list ; utility function for storing the vector of strings into hashmap ; check for sorted string if it already exists ; push new string to already existing key ; print utility function for printing all the anagrams ; 

from collections import defaultdict


def printAnagram(store: dict) -> None:
    for (k, v) in store .items():
        temp_vec = v
        size = len(temp_vec)
        if (size > 1):
            for i in range(size):
                print(temp_vec[i], end=" ")
            print()


def storeInMap(vec: list) -> None:
    store = defaultdict(lambda: list)
    for i in range(len(vec)):
        tempString = vec[i]
        tempString = ''.join(sorted(tempString))
        if (tempString not in store):
            temp_vec = []
            temp_vec .append(vec[i])
            store[tempString] = temp_vec
        else:
            temp_vec = store[tempString]
            temp_vec .append(vec[i])
            store[tempString] = temp_vec
    printAnagram(store)


if __name__ == "__main__":
    arr = []
    arr .append("geeksquiz")
    arr .append("geeksforgeeks")
    arr .append("abcd")
    arr .append("forgeeksgeeks")
    arr .append("zuiqkeegs")
    arr .append("cat")
    arr .append("act")
    arr .append("tca")
    storeInMap(arr)

# Expected output:
geeksquiz zuiqkeegs 
geeksforgeeks forgeeksgeeks 
cat act tca
# quick way to check if all the characters of a string are same | function to check is all the characters in string are or not ; insert characters in the set ; if all characters are same size of set will always be 1 ; 
def allCharactersSame(s):
    s1 = []
    for i in range(len(s)):
        s1 .append(s[i])
    s1 = list(set(s1))
    if (len(s1) == 1):
        print("YES")
    else:
        print("NO")


Str = "nnnn"
allCharactersSame(Str)

# Expected output:
YES
# check if both halves of the string have same set of characters | python3 program to check if it is possible to split string or not ; function to check if we can split string or not ; counter array 

MAX_CHAR = 26


def checkCorrectOrNot(s):
    global MAX_CHAR
    count1 = [0] * MAX_CHAR
    count2 = [0] * MAX_CHAR
    n = len(s)
    if n == 1:
        return true
    i = 0
    j = n - 1
    while (i < j):
        count1[ord(s[i]) - ord('a')] += 1
        count2[ord(s[j]) - ord('a')] += 1
        i += 1
        j -= 1
    for i in range(MAX_CHAR):
        if count1[i] != count2[i]:
            return False
    return True


s = "ababc"
print("Yes"if checkCorrectOrNot(s)else "No")

# Expected output:
No
# extract maximum numeric value from a given string | set 1 ( general approach ) | utility function to find maximum string ; if both having equal lengths ; reach first unmatched character / value ; return string with maximum value ; if different lengths return string with maximum length ; function to extract the maximum value ; start traversing the string ; ignore leading zeroes ; store numeric value into a string ; update maximum string ; to handle the case if there is only 0 numeric value ; return maximum string ; 
def maximumNum(curr_num, res):
    len1 = len(curr_num)
    len2 = len(res)
    if (len1 == len2):
        i = 0
        while (curr_num[i] == res[i]):
            i += 1
        if (curr_num[i] < res[i]):
            return res
        else:
            return curr_num
    return res if (len1 < len2)else curr_num


def extractMaximum(str):
    n = len(str)
    curr_num = ""
    res = ""
    for i in range(n):
        while (i < n and str[i] == '0'):
            i += 1
        while (i < n and str[i] >= '0' and str[i] <= '9'):
            curr_num += str[i]
            i += 1
        if (i == n):
            break
        if (len(curr_num) > 0):
            i -= 1
        res = maximumNum(curr_num, res)
        curr_num = ""
    if (len(curr_num) == 0 and len(res) == 0):
        res += '0'
    return maximumNum(curr_num, res)


str = "100klh564abc365bg"
print(extractMaximum(str))

# Expected output:
564
# to check divisibility of any large number by 999 | function to check divisibility ; append required 0 s at the beginning . ; add digits in group of three in gsum ; group saves 3 - digit group ; calculate result till 3 digit sum ; 
def isDivisible999(num):
    n = len(num)
    if (n == 0 or num[0] == '0'):
        return true
    if ((n % 3) == 1):
        num = "00" + num
    if ((n % 3) == 2):
        num = "0" + num
    gSum = 0
    for i in range(0, n, 3):
        group = 0
        group += (ord(num[i]) - 48) * 100
        group += (ord(num[i + 1]) - 48) * 10
        group += (ord(num[i + 2]) - 48)
        gSum += group
    if (gSum > 1000):
        num = str(gSum)
        n = len(num)
        gSum = isDivisible999(num)
    return (gSum == 999)


if __name__ == "__main__":
    num = "1998"
    n = len(num)
    if (isDivisible999(num)):
        print("Divisible")
    else:
        print("Not divisible")

# Expected output:
Divisible
# rearrange a string in sorted order followed by the integer sum | python3 program for above implementation ; function to return string in lexicographic order followed by integers sum ; traverse the string ; count occurrence of uppercase alphabets ; store sum of integers ; traverse for all characters a to z ; append the current character in the string no . of times it occurs in the given string ; append the sum of integers ; return resultant string ; 

MAX_CHAR = 26


def arrangeString(string):
    char_count = [0] * MAX_CHAR
    s = 0
    for i in range(len(string)):
        if string[i] >= "A" and string[i] <= "Z":
            char_count[ord(string[i]) - ord("A")] += 1
        else:
            s += ord(string[i]) - ord("0")
    res = ""
    for i in range(MAX_CHAR):
        ch = chr(ord("A") + i)
        while char_count[i]:
            res += ch
            char_count[i] -= 1
    if s > 0:
        res += str(s)
    return res


if __name__ == "__main__":
    string = "ACCBA10D2EW30"
    print(arrangeString(string))

# Expected output:
AABCCDEW6
# program to print all substrings of a given string | function to print all sub strings ; pick starting point ; pick ending point ; print characters from current starting point to current ending point . ; 
def subString(Str, n):
    for Len in range(1, n + 1):
        for i in range(n - Len + 1):
            j = i + Len - 1
            for k in range(i, j + 1):
                print(Str[k], end="")
            print()


Str = "abc"
subString(Str, len(Str))

# Expected output:
a
b
c
ab
bc
abc
# reverse a string preserving space positions | function to reverse the string and preserve the space position ; mark spaces in result ; traverse input string from beginning and put characters in result from end ; ignore spaces in input string ; ignore spaces in result . ; 
def reverses(st):
    n = len(st)
    result = [0] * n
    for i in range(n):
        if (st[i] == ' '):
            result[i] = ' '
    j = n - 1
    for i in range(len(st)):
        if (st[i] != ' '):
            if (result[j] == ' '):
                j -= 1
            result[j] = st[i]
            j -= 1
    return ''.join(result)


if __name__ == "__main__":
    st = "internship at geeks for geeks"
    print(reverses(st))

# Expected output:
skeegrofsk ee gtapi hsn retni
# find uncommon characters of the two strings | size of the hash table ; function to find the uncommon characters of the two strings ; mark presence of each character as 0 in the hash table 'present[] ; for each character of str1 , mark its presence as 1 in 'present[] ; for each character of str2 ; if a character of str2 is also present in str1 , then mark its presence as - 1 ; else mark its presence as 2 ; print all the uncommon characters ; 

MAX_CHAR = 26


def findAndPrintUncommonChars(str1, str2):
    present = [0] * MAX_CHAR
    for i in range(0, MAX_CHAR):
        present[i] = 0

    l1 = len(str1)
    l2 = len(str2)
    for i in range(0, l1):
        present[ord(str1[i]) - ord('a')] = 1
    for i in range(0, l2):
        if (present[ord(str2[i]) - ord('a')] == 1 or
           present[ord(str2[i]) - ord('a')] == -1):
            present[ord(str2[i]) - ord('a')] = -1
        else:
            present[ord(str2[i]) - ord('a')] = 2
    for i in range(0, MAX_CHAR):
        if (present[i] == 1 or present[i] == 2):
            print(chr(i + ord('a')), end=" ")


if __name__ == "__main__":
    str1 = "characters"
    str2 = "alphabets"
    findAndPrintUncommonChars(str1, str2)

# Expected output:
b c l p r
# length of last word in a string | python3 program for implementation of simple approach to find length of last word ; string a is ' final ' -- can not be modified so , create a copy and trim the spaces from both sides ; 
def lengthOfLastWord(a):
    l = 0
    x = a .strip()
    for i in range(len(x)):
        if x[i] == " ":
            l = 0
        else:
            l += 1
    return l


if __name__ == "__main__":
    inp = "Geeks For Geeks "
    print("The length of last word is", lengthOfLastWord(inp))

# Expected output:
The length of last word is 5
# length of last word in a string | python3 program for implementation of efficient approach to find length of last word ; split by space and converting string to list and ; 
def length(str):
    lis = list(str .split(" "))
    return len(lis[-1])


str = "Geeks for Geeks"
print("The length of last word is", length(str))

# Expected output:
The length of last word is 5
# program to count vowels in a string ( iterative and recursive ) | function to check the vowel ; returns count of vowels in str ; check for vowel ; 
def isVowel(ch):
    return ch .upper() in ['A', 'E', 'I', 'O', 'U']


def countVowels(str):
    count = 0
    for i in range(len(str)):
        if isVowel(str[i]):
            count += 1
    return count


str = 'abc de'
print(countVowels(str))

# Expected output:
2
# toggle case of a string using bitwise operators | python3 program to get toggle case of a string ; toggle case = swaps caps to lower case and lower case to caps ; bitwise exor with 32 ; 

x = 32


def toggleCase(a):
    for i in range(len(a)):
        a = a[:i] + chr(ord(a[i]) ^ 32) + a[i + 1:]
    return a


str = "CheRrY"
print("Toggle case: ", end="")
str = toggleCase(str)
print(str)
print("Original string: ", end="")
str = toggleCase(str)
print(str)

# Expected output:
Toggle case: cHErRy
Original string: CheRrY
# determine if a string has all unique characters | python3 program to illustrate string with unique characters ; converting string to set ; if length of set is equal to len of string then it will have unique characters ; 
def uniqueCharacters(str):
    setstring = set(str)
    if (len(setstring) == len(str)):
        return True
    return False


if __name__ == '__main__':
    input = "GeeksforGeeks"
    if (uniqueCharacters(input)):
        print("The String " + input + " has all unique characters")
    else:
        print("The String " + input + " has duplicate characters")

# Expected output:
The String GeeksforGeeks has duplicate characters
# ropes data structure ( fast string concatenation ) | function that concatenates strings a [ 0. . n1 - 1 ] and b [ 0. . n2 - 1 ] and stores the result in c [ ] ; copy characters of a [ ] to c [ ] ; copy characters of b [ ] ; 
def concatenate(a, b, c, n1, n2):
    i = -1
    for i in range(n1):
        c[i] = a[i]
    for j in range(n2):
        c[i] = b[j]
        i += 1


if __name__ == "__main__":
    a = "Hi This is geeksforgeeks. "
    n1 = len(a)
    b = "You are welcome here."
    n2 = len(b)
    a = list(a)
    b = list(b)
    c = [0] * (n1 + n2 - 1)
    concatenate(a, b, c, n1, n2)
    for i in c:
        print(i, end="")

# Expected output:
Hi This is geeksforgeeks.You are welcome here.
# binary representation of next greater number with same number of 1 ' s ▁ and ▁ 0' s | function to find the next greater number with same number of 1 ' s ▁ and ▁ 0' s ; locate first ' i ' from end such that bnum [ i ] == '0' and bnum [ i + 1 ] == '1' swap these value and break ; if no swapping performed ; since we want the smallest next value , shift all 1 ' s ▁ at ▁ the ▁ end ▁ in ▁ the ▁ binary ▁ ▁ substring ▁ starting ▁ from ▁ index ▁ ' i + 2 ; special case while swapping if '0' occurs then break ; required next greater number ; 
def nextGreaterWithSameDigits(bnum):
    l = len(bnum)
    bnum = list(bnum)
    for i in range(l - 2, 0, -1):
        if (bnum[i] == '0' and bnum[i + 1] == '1'):
            ch = bnum[i]
            bnum[i] = bnum[i + 1]
            bnum[i + 1] = ch
            break
    if (i == 0):
        return "no greater number"

    j = i + 2
    k = l - 1
    while (j < k):
        if (bnum[j] == '1' and bnum[k] == '0'):
            ch = bnum[j]
            bnum[j] = bnum[k]
            bnum[k] = ch
            j += 1
            k -= 1
        elif (bnum[i] == '0'):
            break
        else:
            j += 1
    return bnum


bnum = "10010"
print("Binary representation of next greater number = ",
      *nextGreaterWithSameDigits(bnum), sep="")

# Expected output:
Binary representation of next greater number = 10100
# generate all rotations of a given string | print all the rotated strings . ; generate all rotations one by one and print ; current index in str ; current index in temp ; copying the second part from the point of rotation . ; copying the first part from the point of rotation . ; 
def printRotatedString(str):
    lenn = len(str)
    temp = [0] * (lenn)
    for i in range(lenn):
        j = i
        k = 0
        while (j < len(str)):
            temp[k] = str[j]
            k += 1
            j += 1
        j = 0
        while (j < i):
            temp[k] = str[j]
            j += 1
            k += 1
        print(*temp, sep="")


if __name__ == '__main__':
    str = "geeks"
    printRotatedString(str)

# Expected output:
geeks
eeksg
eksge
ksgee
sgeek
# all possible strings of any length that can be formed from a given string | python3 code to generate all possible strings that can be formed from given string ; number of subsequences is ( 2 * * n - 1 ) ; generate all subsequences of a given string . using counter 000. . 1 to 111. . 1 ; check if jth bit in the counter is set if set then print jth element from arr [ ] ; print all permutations of current subsequence ; 

from itertools import permutations


def printAll(st):
    n = len(st)
    opsize = pow(2, n)
    for counter in range(1, opsize):
        subs = ""
        for j in range(n):
            if (counter & (1 << j)):
                subs += (st[j])
        perm = permutations(subs)
        for i in perm:
            print(''.join(i), end=" ")


if __name__ == "__main__":
    st = "abc"
    printAll((st))

# Expected output:
a b ab ba c ac ca bc cb abc acb bac bca cab cba
# longest non | utility function to check whether a string is palindrome or not ; check for palindrome . ; palindrome string ; function to find maximum length substring which is not palindrome ; to check whether all characters of the string are same or not ; all characters are same , we can 't  make a non-palindromic string. ; if string is palindrome , we can make it non - palindrome by removing any corner character ; complete string is not a palindrome . ; 
def isPalindrome(str):
    n = len(str)
    for i in range(n // 2):
        if (str[i] != str[n - i - 1]):
            return False
    return True


def maxLengthNonPalinSubstring(str):
    n = len(str)
    ch = str[0]
    i = 1
    for i in range(1, n):
        if (str[i] != ch):
            break
    if (i == n):
        return 0
    if (isPalindrome(str)):
        return n - 1
    return n


if __name__ == "__main__":
    str = "abba"
    print("Maximum length =", maxLengthNonPalinSubstring(str))

# Expected output:
Maximum length = 3
# move spaces to front of string in single traversal | function to find spaces and move to beginning ; traverse from end and swap spaces ; 
def swap(c, i, j):
    c = list(c)
    c[i], c[j] = c[j], c[i]
    return ''.join(c)

def moveSpaceInFront(s):
    i = len(s) - 1
    for j in range(i, -1, -1):
        if (s[j] != ' '):
            s = swap(s, i, j)
            i -= 1
    return s


s = "Hey there, it's GeeksforGeeks"
s = moveSpaceInFront(s)
print(s)

# Expected output:
   Heythere,it'sGeeksforGeeks