giulio98/xlcost-single-prompt huggingface dataset:
# digital root of a given large integer using recursion | function to convert given sum into string ; loop to extract digit one by one from the given sum and concatenate into the string ; type casting for concatenation ; return converted string ; function to get individual digit sum from string ; loop to get individual digit sum ; function call to convert sum into string ; function to calculate the digital root of a very large number ; base condition ; function call to get individual digit sum ; recursive function to get digital root of a very large number ; 
def convertToString(sum):
    str1 = ""
    while (sum):
        str1 = str1 + chr((sum % 10) + ord('0'))
        sum = sum // 10
    return str1


def GetIndividulaDigitSum(str1, len1):
    sum = 0
    for i in range(len1):
        sum = sum + ord(str1[i]) - ord('0')
    return convertToString(sum)


def GetDigitalRoot(str1):
    if (len(str1) == 1):
        return ord(str1[0]) - ord('0')
    str1 = GetIndividulaDigitSum(str1, len(str1))
    return GetDigitalRoot(str1)


if __name__ == '__main__':
    str1 = "675987890789756545689070986776987"
    print(GetDigitalRoot(str1))

# Expected output:
5
# count the number of matching characters in a pair of strings | function to count the matching characters ; traverse the string 1 char by char ; this will check if str1 [ i ] is present in str2 or not str2 . find ( str1 [ i ] ) returns - 1 if not found otherwise it returns the starting occurrence index of that character in str2 ; 
def count(str1, str2):
    c = 0
    j = 0
    for i in range(len(str1)):
        if str1[i] in str2:
            c += 1
        j += 1
    print("No. of matching characters are: ", c)


if __name__ == "__main__":
    str1 = "aabcddekll12@"
    str2 = "bb2211@55k"
    count(str1, str2)

# Expected output:
No. of matching characters are:  5
# check if count of alphabets and count of numbers are equal in the given string | function to count the number of alphabets ; counter to store the number of alphabets in the string ; every character in the string is iterated ; to check if the character is an alphabet or not ; function to count the number of numbers ; counter to store the number of alphabets in the string ; every character in the string is iterated ; to check if the character is a digit or not ; function to check if the count of alphabets is equal to the count of numbers or not ; 
def countOfLetters(string):
    letter = 0
    for i in range(len(string)):
        if ((string[i] >= 'A' and string[i] <= 'Z') or (
                string[i] >= 'a' and string[i] <= 'z')):
            letter += 1
    return letter


def countOfNumbers(string):
    number = 0
    for i in range(len(string)):
        if (string[i] >= '0' and string[i] <= '9'):
            number += 1
    return number


def check(string):
    if (countOfLetters(string) == countOfNumbers(string)):
        print("Yes")
    else:
        print("No")


if __name__ == "__main__":
    string = "GeeKs01324"
    check(string)

# Expected output:
Yes
# index of character depending on frequency count in string | python3 implementation of the approach ; function to perform the queries ; l [ i ] [ j ] stores the largest i such that ith character appears exactly jth times in str [ 0. . . i ] ; f [ i ] [ j ] stores the smallest i such that ith character appears exactly jth times in str [ 0. . . i ] ; to store the frequency of each of the character of str ; current character of str ; update its frequency ; for every lowercase character of the english alphabet ; if it is equal to the character under consideration then update l [ ] [ ] and r [ ] [ ] as it is cnt [ j ] th occurrence of character k ; only update l [ ] [ ] as k has not been occurred so only index has to be incremented ; perform the queries ; type 1 query ; type 2 query ; 

import numpy as np
MAX = 26


def performQueries(string, q, type_arr, ch, freq):
    n = len(string)
    L = np .zeros((MAX, n))
    F = np .zeros((MAX, n))
    cnt = [0] * MAX
    for i in range(n):
        k = ord(string[i]) - ord('a')
        cnt[k] += 1
        for j in range(MAX):
            if (k == j):
                L[j][cnt[j]] = i
                F[j][cnt[j]] = i
            else:
                L[j][cnt[j]] = L[j][cnt[j]] + 1
    for i in range(q):
        if (type_arr[i] == 1):
            print(L[ord(ch[i]) - ord('a')][freq[i]], end="")
        else:
            print(F[ord(ch[i]) - ord('a')][freq[i]], end="")
        print()


if __name__ == "__main__":
    string = "geeksforgeeks"
    type_arr = [1, 2]
    ch = ['e', 'k']
    freq = [2, 2]
    q = len(type_arr)
    performQueries(string, q, type_arr, ch, freq)

# Expected output:
8.0
11.0
# number of index pairs such that s [ i ] and s [ j ] are anagrams | function to find number of pairs of integers i , j such that s [ i ] is an anagram of s [ j ] . ; to store the count of sorted strings ; traverse all strings and store in the map ; sort the string ; if string exists in map , increment count else create key value pair with count = 1 ; to store the number of pairs ; traverse through the map ; count the pairs for each string ; return the required answer ; 
def anagram_pairs(s, n):
    mp = dict()
    for i in range(n):
        temp_str = "".join(sorted(s[i]))
        if temp_str in mp:
            mp[temp_str] += 1
        else:
            mp[temp_str] = 1
    ans = 0
    for k in mp .values():
        ans += (k * (k - 1)) // 2
    return ans


if __name__ == "__main__":
    s = ["aaab", "aaba", "baaa", "cde", "dec"]
    n = len(s)
    print(anagram_pairs(s, n))

# Expected output:
4
# insert a character in a rotated string | function to insert the character ; to store last position where the insertion is done ; to store size of the string ; to store the modified string ; to store characters ; add first character to the string ; update the size ; update the index of last insertion ; insert all other characters to the string ; take the character ; take substring upto ind ; take modulo value of k with the size of the string ; check if we need to move to the start of the string ; if we don 't need to move to start of the string ; take substring from upto temp ; take substring which will be after the inserted character ; insert into the string ; store new inserted position ; store size of the new string technically sz + 1 ; if we need to move to start of the string ; take substring which will before the inserted character ; take substring which will be after the inserted character ; insert into the string ; store new inserted position ; store size of the new string technically sz + 1 ; return the required character ; 
def insert(arr: list, n: int, k: int) -> chr:
    ind = 0
    sz = 0
    s = ""
    ch = arr[0]
    s += ch
    sz = 1
    ind = 0
    for i in range(1, n):
        ch = arr[i]
        s1 = s[0:ind + 1]
        temp = k % sz
        ro = temp - min(temp, sz - ind - 1)
        if ro == 0:
            s2 = s[ind + 1:ind + 1 + temp]
            s3 = s[ind + temp + 1:sz]
            s = s1 + s2 + ch + s3
            ind = len(s1) + len(s2)
            sz = len(s)
        else:
            s2 = s[:ro]
            s3 = s[ro:sz]
            s = s2 + ch + s3
            ind = len(s2)
            sz = len(s)
    if ind == 0:
        return s[sz - 1]
    else:
        return s[ind - 1]


if __name__ == "__main__":
    arr = ['1', '2', '3', '4', '5']
    k = 2
    n = len(arr)
    print(insert(arr, n, k))

# Expected output:
1
# rearrange the given string such that all prime multiple indexes have same character | python3 program to rearrange the given string such that all prime multiple indexes have same character ; to store answer ; function to rearrange the given string such that all prime multiple indexes have the same character . ; initially assume that we can kept any symbol at any positions . if at any index contains one then it is not counted in our required positions ; to store number of positions required to store elements of same kind ; start sieve ; for all multiples of i ; map to store frequency of each character ; store all characters in the vector and sort the vector to find the character with highest frequency ; if most occured character is less than required positions ; in all required positions keep character which occured most times ; fill all other indexes with remaining characters ; if character frequency becomes zero then go to next character ; 

N = 100005
ans = [0] * N


def Rearrange(s, n):
    sieve = [1] * (N + 1)
    sz = 0
    for i in range(2, n // 2 + 1):
        if (sieve[i]):
            for j in range(1, n // i + 1):
                if (sieve[i * j]):
                    sz += 1
                sieve[i * j] = 0
    m = dict .fromkeys(s, 0)
    for it in s:
        m[it] += 1
    v = []
    for key, value in m .items():
        v .append([value, key])
    v .sort()
    if (v[-1][0] < sz):
        print(-1, end="")
        return
    for i in range(2, n + 1):
        if (not sieve[i]):
            ans[i] = v[-1][1]
    idx = 0
    for i in range(1, n + 1):
        if (sieve[i]):
            ans[i] = v[idx][1]
            v[idx][0] -= 1
            if (v[idx][0] == 0):
                idx += 1
        print(ans[i], end="")


if __name__ == "__main__":
    string = "aabaaaa"
    n = len(string)
    Rearrange(string, n)

# Expected output:
baaaaaa
# check loop in array according to given constraints | a simple graph dfs based recursive function to check if there is cycle in graph with vertex v as root of dfs . refer below article for details . https : www . geeksforgeeks . org / detect - cycle - in - a - graph / ; there is a cycle if an adjacent is visited and present in recursion call stack recur [ ] ; returns true if arr [ ] has cycle ; create a graph using given moves in arr [ ] ; do dfs traversal of graph to detect cycle ; 
def isCycleRec(v, adj, visited, recur):
    visited[v] = True
    recur[v] = True
    for i in range(len(adj[v])):
        if (visited[adj[v][i]] == False):
            if (isCycleRec(adj[v][i], adj, visited, recur)):
                return True
        elif (visited[adj[v][i]] and recur[adj[v][i]]):
            return True
    recur[v] = False
    return False


def isCycle(arr, n):
    adj = [[]for i in range(n)]
    for i in range(n):
        if (i != (i + arr[i] + n) % n):
            adj[i].append((i + arr[i] + n) % n)
    visited = [False] * n
    recur = [False] * n
    for i in range(n):
        if (visited[i] == False):
            if (isCycleRec(i, adj, visited, recur)):
                return True
    return True


if __name__ == '__main__':
    arr = [2, -1, 1, 2, 2]
    n = len(arr)
    if (isCycle(arr, n)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# queries to answer the x | function to pre - process the sub - strings in sorted order ; generate all substrings ; iterate to find all sub - strings ; store the sub - string in the vector ; sort the substrings lexicographically ; 
def pre_process(substrings, s):
    n = len(s)
    for i in range(n):
        dup = ""
        for j in range(i, n):
            dup += s[j]
            substrings .append(dup)
    substrings .sort()
    return substrings


if __name__ == "__main__":
    s = "geek"
    substrings = []
    substrings = pre_process(substrings, s)
    queries = [1, 5, 10]
    q = len(queries)
    for i in range(q):
        print(substrings[queries[i] - 1])

# Expected output:
e
ek
k
# minimum cost to modify a string | function to return the minimum cost ; initialize result ; to store the frequency of characters of the string ; update the frequencies of the characters of the string ; loop to check all windows from a - z where window size is k ; starting index of window ; ending index of window ; check if the string contains character ; check if the character is on left side of window find the cost of modification for character add value to count calculate nearest distance of modification ; check if the character is on right side of window find the cost of modification for character add value to count calculate nearest distance of modification ; find the minimum of all costs for modifying the string ; loop to check all windows here window contains characters before z and after z of window size k ; starting index of window ; ending index of window ; check if the string contains character ; if characters are outside window find the cost for modifying character add value to count ; find the minimum of all costs for modifying the string ; 
def minCost(str1, K):
    n = len(str1)
    res = 999999999
    count = 0
    cnt = [0 for i in range(27)]
    for i in range(n):
        cnt[ord(str1[i]) - ord('a') + 1] += 1
    for i in range(1, 26 - K + 1, 1):
        a = i
        b = i + K
        count = 0
        for j in range(1, 27, 1):
            if (cnt[j] > 0):
                if (j >= a and j >= b):
                    count = count + (min(j - b, 25 - j + a + 1)) * cnt[j]
                elif (j <= a and j <= b):
                    count = count + (min(a - j, 25 + j - b + 1)) * cnt[j]
        res = min(res, count)
    for i in range(26 - K + 1, 27, 1):
        a = i
        b = (i + K) % 26
        count = 0
        for j in range(1, 27, 1):
            if (cnt[j] > 0):
                if (j >= b and j <= a):
                    count = count + (min(j - b, a - j)) * cnt[j]
        res = min(res, count)
    return res


if __name__ == '__main__':
    str1 = "abcdefghi"
    K = 2
    print(minCost(str1, K))

# Expected output:
12
# generate all binary strings of length n with sub | utility function to print the given binary string ; this function will be called recursively to generate the next bit for given binary string according to its current state ; base - case : if the generated binary string meets the required length and the pattern "01" appears twice ; nextbit needs to be 0 because each time we call the function recursively , we call 2 times for 2 cases : next bit is 0 or 1 the is to assure that the binary string is printed one time only ; generate the next bit for str and call recursive ; assign first bit ; the next generated bit will either be 0 or 1 ; if pattern "01" occurrence is < 2 ; set next bit ; if pattern "01" appears then increase the occurrence of pattern ; else pattern "01" occurrence equals 2 ; if previous bit is 0 then next bit cannot be 1 ; otherwise ; 
def printBinStr(string, length):
    for i in range(0, length):
        print(string[i], end="")
    print()


def generateBinStr(string, length, currlen, occur, nextbit):
    if currlen == length:
        if occur == 2 and nextbit == 0:
            printBinStr(string, length)
        return
    if currlen == 0:
        string[0] = nextbit
        generateBinStr(string, length, currlen + 1, occur, 0)
        generateBinStr(string, length, currlen + 1, occur, 1)
    else:
        if occur < 2:
            string[currlen] = nextbit
            if string[currlen - 1] == 0 and nextbit == 1:
                occur += 1
            generateBinStr(string, length, currlen + 1, occur, 0)
            generateBinStr(string, length, currlen + 1, occur, 1)
        else:
            if string[currlen - 1] == 0 and nextbit == 1:
                return
            else:
                string[currlen] = nextbit
                generateBinStr(string, length, currlen + 1, occur, 0)
                generateBinStr(string, length, currlen + 1, occur, 1)


if __name__ == "__main__":
    n = 5
    if n < 4:
        print(-1)
    else:
        string = [None] * n
        generateBinStr(string, n, 0, 0, 0)
        generateBinStr(string, n, 0, 0, 1)

# Expected output:
00101
01001
01010
01011
01101
10101
# print last character of each word in a string | function to print the last character of each word in the given string ; now , last word is also followed by a space ; if current character is a space ; then previous character must be the last character of some word ; 
def printLastChar(string):
    string = string + " "
    for i in range(len(string)):
        if string[i] == ' ':
            print(string[i - 1], end=" ")


string = "Geeks for Geeks"
printLastChar(string)

# Expected output:
s r s
# maximum length of balanced string after swapping and removal of characters | function to return the length of the longest balanced sub - string ; to store the count of parentheses ; traversing the string ; check type of parentheses and incrementing count for it ; sum all pair of balanced parentheses ; 
def maxBalancedStr(s):
    open1 = 0
    close1 = 0
    open2 = 0
    close2 = 0
    open3 = 0
    close3 = 0
    for i in range(len(s)):
        if (s[i] == '('):
            open1 += 1
            continue
        if s[i] == ')':
            close1 += 1
            continue
        if s[i] == '{':
            open2 += 1
            continue
        if s[i] == '}':
            close2 += 1
            continue
        if s[i] == '[':
            open3 += 1
            continue
        if s[i] == ']':
            close3 += 1
            continue
    maxLen = (2 * min(open1, close1) + 2 *
              min(open2, close2) + 2 * min(open3, close3))
    return maxLen


if __name__ == '__main__':
    s = "))[]](("
    print(maxBalancedStr(s))

# Expected output:
6
# bitwise or of n binary strings | function to return the bitwise or of all the binary strings ; get max size and reverse each string since we have to perform or operation on bits from right to left reversing the string will make it easier to perform operation from left to right ; add 0 s to the end of strings if needed ; perform or operation on each bit ; reverse the resultant string to get the final string ; return the final string ; 
def strBitwiseOR(arr, n):
    res = ""
    max_size = -(2 ** 32)
    for i in range(n):
        max_size = max(max_size, len(arr[i]))
        arr[i] = arr[i][::-1]
    for i in range(n):
        s = ""
        for j in range(max_size - len(arr[i])):
            s += '0'
        arr[i] = arr[i] + s
    for i in range(max_size):
        curr_bit = 0
        for j in range(n):
            curr_bit = curr_bit | ord(arr[j][i])
        res += chr(curr_bit)
    res = res[::-1]
    return res


arr = ["10", "11", "1000001"]
n = len(arr)
print(strBitwiseOR(arr, n))

# Expected output:
1000011
# minimum cost to make two strings same | function to return the minimum cost to make the configuration of both the strings same ; iterate and find the cost ; find the minimum cost ; 
def findCost(s1, s2, a, b, c, d, n):
    cost = 0
    for i in range(n):
        if (s1[i] == s2[i]):
            continue
        else:
            if ((s1[i] == '1' and s2[i] == '2') or (
                    s2[i] == '1' and s1[i] == '2')):
                cost += min(d, min(a, b + c))
            elif ((s1[i] == '2' and s2[i] == '3') or (s2[i] == '2' and s1[i] == '3')):
                cost += min(d, min(b, a + c))
            elif ((s1[i] == '1' and s2[i] == '3') or (s2[i] == '1' and s1[i] == '3')):
                cost += min(d, min(c, a + b))
    return cost


if __name__ == '__main__':
    s1 = "121"
    s2 = "223"
    a = 2
    b = 3
    c = 4
    d = 10
    n = len(s1)
    print(findCost(s1, s2, a, b, c, d, n))

# Expected output:
6
# count the number of common divisors of the given strings | function that returns true if sub - string s [ 0. . . k ] is repeated a number of times to generate string s ; function to return the count of common divisors ; if the length of the sub - string divides length of both the strings ; if prefixes match in both the strings ; if both the strings can be generated ; 
def check(s, k):
    for i in range(0, len(s)):
        if (s[i] != s[i % k]):
            return False
    return True


def countCommonDivisors(a, b):
    ct = 0
    n = len(a)
    m = len(b)
    for i in range(1, min(n, m) + 1):
        if (n % i == 0 and m % i == 0):
            if (a[0:i] == b[0:i]):
                if (check(a, i) and check(b, i)):
                    ct = ct + 1
    return ct


a = "xaxa"
b = "xaxaxaxa"
print(countCommonDivisors(a, b))

# Expected output:
2
# level order traversal line by line | set 3 ( using one queue ) | python3 program to print levels line by line ; a binary tree node ; function to do level order traversal line by line ; create an empty queue for level order traversal ; pushing root node into the queue . ; pushing delimiter into the queue . ; condition to check occurrence of next level . ; pushing left child of current node . ; pushing left child current node ; pushing right child of current node . ; 

from collections import deque as queue


class Node:
    def __init__(self, key):
        self .data = key
        self .left = None
        self .right = None


def levelOrder(root):
    if (root is None):
        return
    q = queue()
    q .append(root)
    q .append(None)
    while (len(q) > 1):
        curr = q .popleft()
        if (curr is None):
            q .append(None)
            print()
        else:
            if (curr .left):
                q .append(curr .left)
            if (curr .right):
                q .append(curr .right)
            print(curr .data, end=" ")


if __name__ == '__main__':
    root = Node(1)
    root .left = Node(2)
    root .right = Node(3)
    root .left .left = Node(4)
    root .left .right = Node(5)
    root .right .right = Node(6)
    levelOrder(root)

# Expected output:
1 
2 3 
4 5 6
# convert given string so that it holds only distinct characters | function to return the index of the character that has 0 occurrence starting from index i ; if current character has 0 occurrence ; if no character has 0 occurrence ; function to return the modified string which consists of distinct characters ; string cannot consist of all distinct characters ; count the occurrences for each of the character ; index for the first character that hasn 't appeared in the string ; if current character appeared more than once then it has to be replaced with some character that hasn 't occurred yet ; decrement current character 's occurrence by 1 ; replace the character ; update the new character ' s ▁ occurrence ▁ ▁ this ▁ step ▁ can ▁ also ▁ be ▁ skipped ▁ as ▁ ▁ we ' ll never encounter this character in the string because it has been added just now ; find the next character that hasn 't occurred yet ; 
def nextZero(i, occurrences):
    while i < 26:
        if occurrences[i] == 0:
            return i
        i += 1
    return -1


def getModifiedString(str):
    n = len(str)
    if n > 26:
        return "-1"
    ch = str
    ch = list(ch)
    occurrences = [0] * 26
    for i in range(n):
        occurrences[ord(ch[i]) - ord('a')] += 1
    index = nextZero(0, occurrences)
    for i in range(n):
        if occurrences[ord(ch[i]) - ord('a')] > 1:
            occurrences[ord(ch[i]) - ord('a')] -= 1
            ch[i] = chr(ord('a') + index)
            occurrences[index] = 1
            index = nextZero(index + 1, occurrences)
    ch = ''.join(ch)
    print(ch)


if __name__ == "__main__":
    str = "geeksforgeeks"
    getModifiedString(str)

# Expected output:
abcdhforgieks
# replace all occurrences of a string with space | function to extract the secret message ; replacing all occurrences of sub in str by empty spaces ; removing unwanted spaces in the start and end of the string ; 
def extractSecretMessage(Str, Sub):
    Str = Str .replace(Sub, " ")
    return Str .strip()


Str = "LIELIEILIEAMLIECOOL"
Sub = "LIE"
print(extractSecretMessage(Str, Sub))

# Expected output:
I AM COOL
# sub | function to return the count of sub - strings starting from startindex that are also the prefixes of string ; function to return the count of all possible sub - strings of string that are also the prefixes of string ; if current character is equal to the starting character of str ; 
def subStringsStartingHere(string, n, startIndex):
    count = 0
    i = startIndex + 1
    while (i <= n):
        if string .startswith(string[startIndex:i]):
            count += 1
        else:
            break
        i += 1
    return count


def countSubStrings(string, n):
    count = 0
    for i in range(n):
        if string[i] == string[0]:
            count += subStringsStartingHere(string, n, i)
    return count


if __name__ == "__main__":
    string = "ababc"
    n = len(string)
    print(countSubStrings(string, n))

# Expected output:
7