giulio98/xlcost-single-prompt huggingface dataset:
# sort a string according to the order defined by another string | python3 program to sort a string according to the order defined by a pattern string ; sort str according to the order defined by pattern . ; create a count array store count of characters in str . ; count number of occurrences of each character in str . ; traverse the pattern and print every characters same number of times as it appears in str . this loop takes o ( m + n ) time where m is length of pattern and n is length of str . ; 

MAX_CHAR = 26


def sortByPattern(str, pat):
    global MAX_CHAR
    count = [0] * MAX_CHAR
    for i in range(0, len(str)):
        count[ord(str[i]) - 97] += 1
    index = 0
    str = ""
    for i in range(0, len(pat)):
        j = 0
        while (j < count[ord(pat[i]) - ord('a')]):
            str += pat[i]
            j = j + 1
            index += 1
    return str


pat = "bca"
str = "abc"
print(sortByPattern(str, pat))

# Expected output:
bca
# number of flips to make binary string alternate | set 1 | utility method to flip a character ; utility method to get minimum flips when alternate string starts with expected char ; if current character is not expected , increase flip count ; flip expected character each time ; method return minimum flip to make binary string alternate ; return minimum of following two 1 ) flips when alternate string starts with 0 2 ) flips when alternate string starts with 1 ; 
def flip(ch):
    return '1'if (ch == '0')else '0'


def getFlipWithStartingCharcter(str, expected):
    flipCount = 0
    for i in range(len(str)):
        if (str[i] != expected):
            flipCount += 1
        expected = flip(expected)
    return flipCount


def minFlipToMakeStringAlternate(str):
    return min(
        getFlipWithStartingCharcter(
            str, '0'), getFlipWithStartingCharcter(
            str, '1'))


if __name__ == "__main__":
    str = "0001010111"
    print(minFlipToMakeStringAlternate(str))

# Expected output:
2
# remainder with 7 for large numbers | function which return remainder after dividing the number by 7 ; this series is used to find remainder with 7 ; index of next element in series ; initialize result ; traverse num from end ; find current digit of num ; add next term to result ; move to next term in series ; make sure that result never goes beyond 7. ; make sure that remainder is positive ; 
def remainderWith7(num):
    series = [1, 3, 2, -1, -3, -2]
    series_index = 0
    result = 0
    for i in range((len(num) - 1), -1, -1):
        digit = ord(num[i]) - 48
        result += digit * series[series_index]
        series_index = (series_index + 1) % 6
        result %= 7
    if (result < 0):
        result = (result + 7) % 7
    return result


str = "12345"
print("Remainder with 7 is", remainderWith7(str))

# Expected output:
Remainder with 7 is 4
# check if a string can become empty by recursively deleting a given sub | returns true if str can be made empty by recursively removing sub_str . ; idx : to store starting index of sub - string found in the original string ; erasing the found sub - string from the original string ; 
def canBecomeEmpty(string, sub_str):
    while len(string) > 0:
        idx = string .find(sub_str)
        if idx == -1:
            break
        string = string .replace(sub_str, "", 1)
    return (len(string) == 0)


if __name__ == "__main__":
    string = "GEEGEEKSKS"
    sub_str = "GEEKS"
    if canBecomeEmpty(string, sub_str):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# perfect reversible string | this function basically checks if string is palindrome or not ; iterate from left and right ; 
def isReversible(str):
    i = 0
    j = len(str) - 1
    while (i < j):
        if (str[i] != str[j]):
            return False
        i += 1
        j -= 1
    return True


str = "aba"
if (isReversible(str)):
    print("YES")
else:
    print("NO")

# Expected output:
YES
# check if string follows order of characters defined by a pattern or not | set 3 | python3 program to find if a string follows order defined by a given pattern ; returns true if characters of str follow order defined by a given ptr . ; initialize all orders as - 1 ; assign an order to pattern characters according to their appearance in pattern ; give the pattern characters order ; increment the order ; now one by one check if string characters follow above order ; if order of this character is less than order of previous , return false ; update last_order for next iteration ; return that str followed pat ; 

CHAR_SIZE = 256


def checkPattern(Str, pat):
    label = [-1] * CHAR_SIZE
    order = 1
    for i in range(len(pat)):
        label[ord(pat[i])] = order
        order += 1
    last_order = -1
    for i in range(len(Str)):
        if (label[ord(Str[i])] != -1):
            if (label[ord(Str[i])] < last_order):
                return False
            last_order = label[ord(Str[i])]
    return True


if __name__ == '__main__':
    Str = "engineers rock"
    pattern = "gsr"
    print(checkPattern(Str, pattern))

# Expected output:
False
# check if string follows order of characters defined by a pattern or not | set 2 | python3 program to check if characters of a string follow pattern defined by given pattern . ; insert all characters of pattern in a hash set , ; build modified string ( string with characters only from pattern are taken ) ; remove more than one consecutive occurrences of pattern characters from modified string . ; after above modifications , the length of modified string must be same as pattern length ; and pattern characters must also be same as modified string characters ; 
def followsPattern(string, pattern):
    patternSet = set()
    for i in range(len(pattern)):
        patternSet .add(pattern[i])
    modifiedString = string
    for i in range(len(string) - 1, -1, -1):
        if not modifiedString[i] in patternSet:
            modifiedString = modifiedString[:i] + modifiedString[i + 1:]
    for i in range(len(modifiedString) - 1, 0, -1):
        if modifiedString[i] == modifiedString[i - 1]:
            modifiedString = modifiedString[:i] + modifiedString[i + 1:]
    if len(pattern) != len(modifiedString):
        return False
    for i in range(len(pattern)):
        if pattern[i] != modifiedString[i]:
            return False
    return True


if __name__ == "__main__":
    string = "engineers rock"
    pattern = "er"
    print("Expected: true, Actual:", followsPattern(string, pattern))
    string = "engineers rock"
    pattern = "egr"
    print("Expected: false, Actual:", followsPattern(string, pattern))
    string = "engineers rock"
    pattern = "gsr"
    print("Expected: false, Actual:", followsPattern(string, pattern))
    string = "engineers rock"
    pattern = "eger"
    print("Expected: true, Actual:", followsPattern(string, pattern))

# Expected output:
Expected: true, Actual: True
Expected: false, Actual: False
Expected: false, Actual: False
Expected: true, Actual: True
# find k 'th character of decrypted string | set 1 | function to find k 'th character in encoded string ; expand string variable is used to store final string after decompressing string str ; current substring freq = 0 count of current substring ; read characters until you find a number or end of string ; push character in temp ; read number for how many times string temp will be repeated in decompressed string ; generating frequency of temp ; now append string temp into expand equal to its frequency ; this condition is to handle the case when string str is ended with alphabets not with numeric value ; 
def encodedChar(str, k):
    expand = ""
    freq = 0
    i = 0
    while (i < len(str)):
        temp = ""
        freq = 0
        while (i < len(str) and
               ord(str[i]) >= ord('a') and
               ord(str[i]) <= ord('z')):
            temp += str[i]
            i += 1
        while (i < len(str) and
               ord(str[i]) >= ord('1') and
               ord(str[i]) <= ord('9')):
            freq = freq * 10 + ord(str[i]) - ord('0')
            i += 1
        for j in range(1, freq + 1, 1):
            expand += temp
    if (freq == 0):
        expand += temp

    return expand[k - 1]


if __name__ == '__main__':
    str = "ab4c12ed3"
    k = 21
    print(encodedChar(str, k))

# Expected output:
e
# converting decimal number lying between 1 to 3999 to roman numerals | function to calculate roman equivalent ; storing roman values of digits from 0 - 9 when placed at different places ; converting to roman ; 
def intToRoman(num):
    m = ["", "M", "MM", "MMM"]
    c = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM "]
    x = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"]
    i = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
    thousands = m[num // 1000]
    hundereds = c[(num % 1000) // 100]
    tens = x[(num % 100) // 10]
    ones = i[num % 10]
    ans = (thousands + hundereds + tens + ones)
    return ans


if __name__ == "__main__":
    number = 3549
    print(intToRoman(number))

# Expected output:
MMMDXLIX
# longest common prefix using binary search | a function to find the string having the minimum length and returns that length ; a function that returns the longest common prefix from the array of strings ; we will do an in - place binary search on the first string of the array in the range 0 to index ; same as ( low + high ) / 2 , but avoids overflow for large low and high ; if all the strings in the input array contains this prefix then append this substring to our answer ; and then go for the right part ; go for the left part ; 
def findMinLength(strList):
    return len(min(arr, key=len))


def allContainsPrefix(strList, str, start, end):
    for i in range(0, len(strList)):
        word = strList[i]
        for j in range(start, end + 1):
            if word[j] != str[j]:
                return False
    return True


def CommonPrefix(strList):
    prefix = ""
    index = findMinLength(strList)
    low, high = 0, index - 1
    while low <= high:
        mid = int(low + (high - low) / 2)
        if allContainsPrefix(strList, strList[0], low, mid):
            prefix = prefix + strList[0][low:mid + 1]
            low = mid + 1
        else:
            high = mid - 1
    return prefix


arr = ["geeksforgeeks", "geeks", "geek", "geezer"]
lcp = CommonPrefix(arr)
if len(lcp) > 0:
    print("The longest common prefix is " + str(lcp))
else:
    print("There is no common prefix")

# Expected output:
The longest common prefix is gee
# lower case to upper case | converts a string to uppercase ; 
def to_upper(s):
    for i in range(len(s)):
        if ('a' <= s[i] <= 'z'):
            s = s[0:i] + chr(ord(s[i]) & (~(1 << 5))) + s[i + 1:]
    return s


if __name__ == '__main__':
    string = "geeksforgeeks"
    print(to_upper(string))

# Expected output:
GEEKSFORGEEKS
# longest common prefix using divide and conquer algorithm | a utility function to find the common prefix between strings - str1 and str2 ; a divide and conquer based function to find the longest common prefix . this is similar to the merge sort technique ; same as ( low + high ) / 2 , but avoids overflow for large low and high ; 
def commonPrefixUtil(str1, str2):
    result = ""
    n1, n2 = len(str1), len(str2)
    i, j = 0, 0
    while i <= n1 - 1 and j <= n2 - 1:
        if str1[i] != str2[j]:
            break
        result += str1[i]
        i, j = i + 1, j + 1
    return result


def commonPrefix(arr, low, high):
    if low == high:
        return arr[low]
    if high > low:
        mid = low + (high - low) // 2
        str1 = commonPrefix(arr, low, mid)
        str2 = commonPrefix(arr, mid + 1, high)
        return commonPrefixUtil(str1, str2)


if __name__ == "__main__":
    arr = ["geeksforgeeks", "geeks", "geek", "geezer"]
    n = len(arr)
    ans = commonPrefix(arr, 0, n - 1)
    if len(ans):
        print("The longest common prefix is", ans)
    else:
        print("There is no common prefix")

# Expected output:
The longest common prefix is gee
# longest common prefix using word by word matching | a utility function to find the common prefix between strings - str1 and str2 ; compare str1 and str2 ; a function that returns the longest common prefix from the array of strings ; 
def commonPrefixUtil(str1, str2):
    result = ""
    n1 = len(str1)
    n2 = len(str2)
    i = 0
    j = 0
    while i <= n1 - 1 and j <= n2 - 1:
        if (str1[i] != str2[j]):
            break
        result += str1[i]
        i += 1
        j += 1
    return (result)


def commonPrefix(arr, n):
    prefix = arr[0]
    for i in range(1, n):
        prefix = commonPrefixUtil(prefix, arr[i])
    return (prefix)


if __name__ == "__main__":
    arr = ["geeksforgeeks", "geeks", "geek", "geezer"]
    n = len(arr)
    ans = commonPrefix(arr, n)
    if (len(ans)):
        print("The longest common prefix is -", ans)
    else:
        print("There is no common prefix")

# Expected output:
The longest common prefix is - gee
# find all strings formed from characters mapped to digits of a number | function to find all strings formed from a given number where each digit maps to given characters . ; vector of strings to store output ; stores index of first occurrence of the digits in input ; maintains index of current digit considered ; for each digit ; store index of first occurrence of the digit in the map ; clear vector contents for future use ; do for each character thats maps to the digit ; for first digit , simply push all its mapped characters in the output list ; from second digit onwards ; for each string in output list append current character to it . ; convert current character to string ; imp - if this is not the first occurrence of the digit , use same character as used in its first occurrence ; store strings formed by current digit ; nothing more needed to be done if this is not the first occurrence of the digit ; replace contents of output list with temp list ; 
def findCombinations(input: list, table: list) -> list:
    out, temp = [], []
    mp = dict()
    index = 0
    for d in input:
        if d not in mp:
            mp[d] = index
        temp .clear()
        for i in range(len(table[d - 1])):
            if index == 0:
                s = table[d - 1][i]
                out .append(s)
            if index > 0:
                for string in out:
                    s = table[d - 1][i]
                    if mp[d] != index:
                        s = string[mp[d]]
                    string = string + s
                    temp .append(string)
                if mp[d] != index:
                    break
        if index > 0:
            out = temp .copy()
        index += 1
    return out


if __name__ == "__main__":
    table = [
        [
            'A', 'B', 'C'], [
            'D', 'E', 'F'], [
                'G', 'H', 'I'], [
                    'J', 'K', 'L'], [
                        'M', 'N', 'O'], [
                            'P', 'Q', 'R'], [
                                'S', 'T', 'U'], [
                                    'V', 'W', 'X'], [
                                        'Y', 'Z']]
    input = [1, 2, 1]
    out = findCombinations(input, table)
    for it in out:
        print(it, end=" ")

# Expected output:
ADA BDB CDC AEA BEB CEC AFA BFB CFC
# 1 ' s ▁ and ▁ 2' s complement of a binary number | returns '0' for '1' and '1' for '0 ; print 1 ' s ▁ and ▁ 2' s complement of binary number represented by " bin " ; for ones complement flip every bit ; for two 's complement go from right  to left in ones complement and if  we get 1 make, we make them 0 and  keep going left when we get first  0, make that 1 and go out of loop ; if no break : all are 1 as in 111 or 11111 in such case , add extra 1 at beginning ; 
def findMinLength(strList):
    return len(min(arr, key=len))


def allContainsPrefix(strList, str, start, end):
    for i in range(0, len(strList)):
        word = strList[i]
        for j in range(start, end + 1):
            if word[j] != str[j]:
                return False
    return True


def CommonPrefix(strList):
    prefix = ""
    index = findMinLength(strList)
    low, high = 0, index - 1
    while low <= high:
        mid = int(low + (high - low) / 2)
        if allContainsPrefix(strList, strList[0], low, mid):
            prefix = prefix + strList[0][low:mid + 1]
            low = mid + 1
        else:
            high = mid - 1
    return prefix


arr = ["geeksforgeeks", "geeks", "geek", "geezer"]
lcp = CommonPrefix(arr)
if len(lcp) > 0:
    print("The longest common prefix is " + str(lcp))
else:
    print("There is no common prefix")

# Expected output:
The longest common prefix is gee
# print concatenation of zig | function for zig - zag concatenation ; check is n is less or equal to 1 ; iterate rownum from 0 to n - 1 ; iterate i till s . length ( ) - 1 ; check is rownum is 0 or n - 1 ; 
def zigZagConcat(s, n):
    if (n <= 1):
        return s
    result = ""
    for rowNum in range(n):
        i = rowNum
        up = True
        while (i < len(s)):
            result += s[i]
            if (rowNum == 0 or rowNum == n - 1):
                i += (2 * n - 2)
            else:
                if (up):
                    i += (2 * (n - rowNum) - 2)
                else:
                    i += rowNum * 2
                up ^= True
    return result


str = "GEEKSFORGEEKS"
n = 3
print(zigZagConcat(str, n))

# Expected output:
GSGSEKFREKEOE
# print string of odd length in ' x ' format | function to print given string in cross pattern ; i and j are the indexes of characters to be displayed in the ith iteration i = 0 initially and go upto length of string j = length of string initially in each iteration of i , we increment i and decrement j , we print character only of k == i or k == j ; 
def pattern(st, length):
    for i in range(length):
        j = length - 1 - i
        for k in range(length):
            if (k == i or k == j):
                print(st[k], end="")
            else:
                print(" ", end="")
        print()


if __name__ == "__main__":
    st = "geeksforgeeks"
    length = len(st)
    pattern(st, length)

# Expected output:
g           s
 e         k 
  e       e  
   k     e   
    s   g    
     f r     
      o      
     f r     
    s   g    
   k     e   
  e       e  
 e         k 
g           s
# check if characters of a given string can be rearranged to form a palindrome | python3 implementation to check if characters of a given string can be rearranged to form a palindrome ; function to check whether characters of a string can form a palindrome ; create a count array and initialize all values as 0 ; for each character in input strings , increment count in the corresponding count array ; count odd occurring characters ; return true if odd count is 0 or 1 , ; 

NO_OF_CHARS = 256


def canFormPalindrome(st):
    count = [0] * (NO_OF_CHARS)
    for i in range(0, len(st)):
        count[ord(st[i])] = count[ord(st[i])] + 1
    odd = 0
    for i in range(0, NO_OF_CHARS):
        if (count[i] & 1):
            odd = odd + 1
        if (odd > 1):
            return False
    return True


if (canFormPalindrome("geeksforgeeks")):
    print("Yes")
else:
    print("No")
if (canFormPalindrome("geeksogeeks")):
    print("Yes")
else:
    print("No")

# Expected output:
No
Yes
# generate n | this function generates all n bit gray codes and prints the generated codes ; base case ; recursive case ; append 0 to the first half ; append 1 to the second half ; function to generate the gray code of n bits ; print contents of arr ; 
def generateGray(n):
    if (n <= 0):
        return ["0"]
    if (n == 1):
        return ["0", "1"]
    recAns = generateGray(n - 1)
    mainAns = []
    for i in range(len(recAns)):
        s = recAns[i]
        mainAns .append("0" + s)
    for i in range(len(recAns) - 1, -1, -1):
        s = recAns[i]
        mainAns .append("1" + s)
    return mainAns


def generateGrayarr(n):
    arr = generateGray(n)
    print(*arr, sep="")


generateGrayarr(3)

# Expected output:
000001011010110111101100
# check whether two strings are anagram of each other | python program to check if two strings are anagrams of each other ; function to check whether two strings are anagram of each other ; create two count arrays and initialize all values as 0 ; for each character in input strings , increment count in the corresponding count array ; if both strings are of different length . removing this condition will make the program fail for strings like " aaca " and " aca " ; compare count arrays ; 

NO_OF_CHARS = 256


def areAnagram(str1, str2):
    count1 = [0] * NO_OF_CHARS
    count2 = [0] * NO_OF_CHARS
    for i in str1:
        count1[ord(i)] += 1
    for i in str2:
        count2[ord(i)] += 1
    if len(str1) != len(str2):
        return 0
    for i in range(NO_OF_CHARS):
        if count1[i] != count2[i]:
            return 0
    return 1


str1 = "geeksforgeeks"
str2 = "forgeeksgeeks"
if areAnagram(str1, str2):
    print("The two strings are anagram of each other")
else:
    print("The two strings are not anagram of each other")

# Expected output:
The two strings are anagram of each other
# find the smallest window in a string containing all characters of another string | python3 program to find the smallest window containing all characters of a pattern . ; function to find smallest window containing all characters of 'pat ; check if string ' s ▁ length ▁ is ▁ ▁ less ▁ than ▁ pattern ' s length . if yes then no such window can exist ; store occurrence ofs characters of pattern ; start traversing the string count = 0 count of characters ; count occurrence of characters of string ; if string ' s ▁ char ▁ matches ▁ with ▁ ▁ pattern ' s char then increment count ; if all the characters are matched ; try to minimize the window ; update window size ; if no window found ; return substring starting from start_index and length min_len ; 

no_of_chars = 256


def findSubString(string, pat):

    len1 = len(string)
    len2 = len(pat)
    if len1 < len2:

        print("No such window exists")
        return ""

    hash_pat = [0] * no_of_chars
    hash_str = [0] * no_of_chars
    for i in range(0, len2):
        hash_pat[ord(pat[i])] += 1

    start, start_index, min_len = 0, -1, float('inf')
    count = 0
    for j in range(0, len1):
        hash_str[ord(string[j])] += 1
        if (hash_str[ord(string[j])] <=
                hash_pat[ord(string[j])]):
            count += 1
        if count == len2:
            while (hash_str[ord(string[start])] >
                   hash_pat[ord(string[start])] or
                   hash_pat[ord(string[start])] == 0):

                if (hash_str[ord(string[start])] >
                        hash_pat[ord(string[start])]):
                    hash_str[ord(string[start])] -= 1
                start += 1
            len_window = j - start + 1
            if min_len > len_window:

                min_len = len_window
                start_index = start
    if start_index == -1:
        print("No such window exists")
        return ""
    return string[start_index: start_index + min_len]


if __name__ == "__main__":

    string = "this is a test string"
    pat = "tist"

    print(findSubString(string, pat))

# Expected output:
t stri
# remove characters from the first string which are present in the second string | python 3 program to remove duplicates ; we extract every character of string string 2 ; we find char exit or not ; if char exit we simply remove that char ; 
def removeChars(string1, string2):
    for i in string2:
        while i in string1:
            itr = string1 .find(i)
            string1 = string1 .replace(i, '')
    return string1


if __name__ == "__main__":
    string1 = "geeksforgeeks"
    string2 = "mask"
    print(removeChars(string1, string2))

# Expected output:
geeforgee