giulio98/xlcost-single-prompt huggingface dataset:
# find the n | function to calculate nth permutation of string ; creating an empty list ; subtracting 1 from n because the permutations start from 0 in factroid method ; loop to generate the factroid of the sequence ; loop to generate nth permutation ; remove 1 - element in each cycle ; final answer ; 
def string_permutation(n, str):
    s = []
    result = ""
    str = list(str)
    n = n - 1
    for i in range(1, len(str) + 1):
        s .append(n % i)
        n = int(n / i)
    for i in range(len(str)):
        a = s[-1]
        result += str[a]
        for j in range(a, len(str) - 1):
            str[j] = str[j + 1]
        str[j + 1] = '\0'
        s .pop()
    print(result)


str = "abcde"
n = 11
string_permutation(n, str)

# Expected output:
acebd
# defanged version of internet protocol address | function to generate a defanged version of ip address . ; loop to iterate over the characters of the string ; 
def GeberateDefangIP(str):
    defangIP = ""
    for c in str:
        if (c == '.'):
            defangIP += "[.]"
        else:
            defangIP += c
    return defangIP


str = "255.100.50.0"
print(GeberateDefangIP(str))

# Expected output:
255[.]100[.]50[.]0
# longest palindromic string formed by concatenation of prefix and suffix of a string | function used to calculate the longest prefix which is also a suffix ; traverse the string ; update the lps size ; returns size of lps ; function to calculate the length of longest palindromic substring which is either a suffix or prefix ; append a character to separate the string and reverse of the string ; reverse the string ; append the reversed string ; function to find the longest palindromic string formed from concatenation of prefix and suffix of a given string ; calculating the length for which prefix is reverse of suffix ; append prefix to the answer ; store the remaining string ; if the remaining string is not empty that means that there can be a palindrome substring which can be added between the suffix & prefix ; calculate the length of longest prefix palindromic substring ; reverse the given string to find the longest palindromic suffix ; calculate the length of longest prefix palindromic substring ; if the prefix palindrome is greater than the suffix palindrome ; append the prefix to the answer ; if the suffix palindrome is greater than the prefix palindrome ; append the suffix to the answer ; finally append the suffix to the answer ; return the answer string ; 
def kmp(s):
    lps = [0] * (len(s))
    for i in range(1, len(s)):
        previous_index = lps[i - 1]
        while (previous_index > 0 and s[i] != s[previous_index]):
            previous_index = lps[previous_index - 1]
        lps[i] = previous_index
        if (s[i] == s[previous_index]):
            lps[i] += 1
    return lps[-1]


def remainingStringLongestPallindrome(s):
    t = s + "?"
    s = s[::-1]
    t += s
    return kmp(t)


def longestPrefixSuffixPallindrome(s):
    length = 0
    n = len(s)
    i = 0
    j = n - 1
    while i < j:
        if (s[i] != s[j]):
            break
        i += 1
        j -= 1
        length += 1
    ans = s[0:length]
    remaining = s[length:length + (n - (2 * length))]
    if (len(remaining)):
        longest_prefix = remainingStringLongestPallindrome(remaining)
        remaining = remaining[::-1]
        longest_suffix = remainingStringLongestPallindrome(remaining)
        if (longest_prefix > longest_suffix):
            remaining = remaining[::-1]
            ans += remaining[0:longest_prefix]
        else:
            ans += remaining[0:longest_suffix]
    ans += s[n - length:n]
    return ans


if __name__ == "__main__":
    st = "rombobinnimor"
    print(longestPrefixSuffixPallindrome(st))

# Expected output:
rominnimor
# generate a string with maximum possible alphabets with odd frequencies | function to generate a string of length n with maximum possible alphabets each occuring odd number of times . ; if n is odd ; add all characters from b - y ; append a to fill the remaining length ; if n is even ; add all characters from b - z ; append a to fill the remaining length ; 
def generateTheString(n):
    ans = ""
    if (n % 2):
        for i in range(min(n, 24)):
            ans += chr(ord('b') + i)
        if (n > 24):
            for i in range((n - 24)):
                ans += 'a'
    else:
        for i in range(min(n, 25)):
            ans += chr(ord('b') + i)
        if (n > 25):
            for i in range((n - 25)):
                ans += 'a'
    return ans


if __name__ == "__main__":
    n = 34
    print(generateTheString(n))

# Expected output:
bcdefghijklmnopqrstuvwxyzaaaaaaaaa
# move all occurrence of letter ' x ' from the string s to the end using recursion | function to move all ' x ' in the end ; store current character ; check if current character is not 'x ; recursive function call ; check if current character is 'x ; 
def moveAtEnd(s, i, l):

    if (i >= l):
        return
    curr = s[i]
    if (curr != 'x'):
        print(curr, end="")
    moveAtEnd(s, i + 1, l)
    if (curr == 'x'):
        print(curr, end="")

    return


if __name__ == '__main__':

    s = "geekxsforgexxeksxx"
    l = len(s)

    moveAtEnd(s, 0, l)

# Expected output:
geeksforgeeksxxxxx
# construct a string of length l such that each substring of length x has exactly y distinct letters | python implementation to construct a string of length l such that each substring of length x has exactly y distinct letters . ; initialize p equal to the ascii value of a ; iterate till the length of the string ; 
def String(l, x, y):
    p = 97
    for j in range(l):
        ans = chr(p + j % y)
        print(ans, end="")


l = 6
x = 5
y = 3
String(l, x, y)

# Expected output:
abcabc
# find the final co | function to print the final position of the point after traversing through the given directions ; traversing through the given directions ; if its north or south the point will move left or right ; if its west or east the point will move upwards or downwards ; returning the final position ; 
def finalCoordinates(SX, SY, D):
    for i in range(len(D)):
        if (D[i] == 'N'):
            SY += 1
        elif (D[i] == 'S'):
            SY -= 1
        elif (D[i] == 'E'):
            SX += 1
        else:
            SX -= 1
    ans = '(' + str(SX) + ',' + str(SY) + ')'
    print(ans)


if __name__ == '__main__':
    SX, SY = 2, 2
    D = "NSSE"
    finalCoordinates(SX, SY, D)

# Expected output:
(3,1)
# frequency of smallest character in first sentence less than that of second sentence | python3 program for the above approach ; function to count the frequency of minimum character ; sort the string s ; return the count with smallest character ; function to count number of frequency of smallest character of string arr1 [ ] is less than the string in arr2 [ ] ; to store the frequency of smallest character in each string of arr2 ; traverse the arr2 [ ] ; count the frequency of smallest character in string s ; append the frequency to freq [ ] ; sort the frequency array ; traverse the array arr1 [ ] ; count the frequency of smallest character in string s ; find the element greater than f ; find the count such that arr1 [ i ] < arr2 [ j ] ; print the count ; 

from bisect import bisect_right as upper_bound


def countMinFreq(s):
    s = sorted(s)
    x = 0
    for i in s:
        if i == s[0]:
            x += 1
    return x


def countLessThan(arr1, arr2):
    freq = []
    for s in arr2:
        f = countMinFreq(s)
        freq .append(f)
    feq = sorted(freq)
    for s in arr1:
        f = countMinFreq(s)
        it = upper_bound(freq, f)
        cnt = len(freq) - it
        print(cnt, end=" ")


if __name__ == '__main__':
    arr1 = ["yyy", "zz"]
    arr2 = ["x", "xx", "xxx", "xxxx"]
    countLessThan(arr1, arr2)

# Expected output:
1 2
# lexicographically all shortest palindromic substrings from a given string | function to find all lexicographically shortest palindromic substring ; array to keep track of alphabetic characters ; iterate to print all lexicographically shortest substring ; 
def shortestPalindrome(s):
    abcd = [0] * 26
    for i in range(len(s)):
        abcd[ord(s[i]) - 97] = 1
    for i in range(26):
        if abcd[i] == 1:
            print(chr(i + 97), end=' ')


s = "geeksforgeeks"
shortestPalindrome(s)

# Expected output:
e f g k o r s
# remove duplicates from string keeping the order according to last occurrences | python3 program to remove duplicate character from character array and print sorted order ; used as index in the modified string ; traverse through all characters ; check if str [ i ] is present before it ; if not present , then add it to result . ; 
def removeDuplicates(str):
    n = len(str)
    res = ""
    for i in range(n):
        j = i + 1
        while j < n:
            if (str[i] == str[j]):
                break
            j += 1
        if (j == n):
            res = res + str[i]
    return res


if __name__ == '__main__':
    str = "geeksforgeeks"
    print(removeDuplicates(str))

# Expected output:
forgeks
# remove duplicates from string keeping the order according to last occurrences | python3 program to remove duplicate character from character array and prin sorted order ; used as index in the modified string ; create an empty hash table ; traverse through all characters from right to left ; if current character is not in ; reverse the result string ; 
def removeDuplicates(str):
    n = len(str)
    s = set()
    res = ""
    for i in range(n - 1, -1, -1):
        if (str[i]not in s):
            res = res + str[i]
            s .add(str[i])
    res = res[::-1]
    return res


str = "geeksforgeeks"
print(removeDuplicates(str))

# Expected output:
forgeks
# count of numbers in a range that does not contain the digit m and which is divisible by m . | function to count all the numbers which does not contain the digit ' m ' and is divisible by m ; storing all the distinct digits of a number ; checking if the two conditions are satisfied or not ; 
def contain(L, U, M):
    count = 0
    for j in range(L, U + 1):
        num = set(str(j))
        if (j % M == 0 and str(M)not in num):
            count += 1
    print(count)


if __name__ == '__main__':
    L = 106
    U = 200
    M = 7
    contain(L, U, M)

# Expected output:
11
# longest string which is prefix string of at least two strings | python3 program to find longest string which is prefix string of at least two strings ; function to find max length of the prefix ; base case ; iterating over all the alphabets ; checking if char exists in current string or not ; if atleast 2 string have that character ; recursive call to i + 1 ; 

max1 = 0


def MaxLength(v, i, m):
    global max1
    if (i >= m):
        return m - 1
    for k in range(26):
        c = chr(ord('a') + k)
        v1 = []
        for j in range(len(v)):
            if (v[j][i] == c):
                v1 .append(v[j])
        if (len(v1) >= 2):
            max1 = max(max1, MaxLength(v1, i + 1, m))
        else:
            max1 = max(max1, i - 1)
    return max1


if __name__ == '__main__':
    s1 = "abcde"
    s2 = "abcsd"
    s3 = "bcsdf"
    s4 = "abcda"
    s5 = "abced"
    v = []
    v .append(s1)
    v .append(s2)
    v .append(s3)
    v .append(s4)
    v .append(s5)
    m = len(v[0])
    print(MaxLength(v, 0, m) + 1)

# Expected output:
4
# periodic binary string with minimum period and a given binary string as subsequence . | function to find the periodic string with minimum period ; print the s if it consists of similar elements ; find the required periodic with period 2 ; 
def findPeriodicString(S):
    l = 2 * len(S)
    count = 0
    for i in range(len(S)):
        if (S[i] == '1'):
            count += 1
    if (count == len(S) or count == 0):
        print(S)
    else:
        arr = ['0'] * l
        for i in range(0, l, 2):
            arr[i] = '1'
            arr[i + 1] = '0'
        for i in range(l):
            print(arr[i], end="")


if __name__ == '__main__':
    S = "1111001"
    findPeriodicString(S)

# Expected output:
10101010101010
# count the minimum number of groups formed in a string | function to count the minimum number of groups formed in the given string s ; initializing count as one since the string is not null ; comparing adjacent characters ; 
def group_formed(S):
    count = 1
    for i in range(len(S) - 1):
        a = S[i]
        b = S[i + 1]
        if (a != b):
            count += 1
    print(count)


if __name__ == "__main__":
    S = "TTWWW"
    group_formed(S)

# Expected output:
2
# find the substring with maximum product | function to return the value of a character ; function to find the maximum product sub ; to store subs ; check if current product is maximum possible or not ; if product is 0 ; return the sub with maximum product ; 
def value(x):
    return (ord(x) - ord('a'))


def maximumProduct(strr, n):
    answer = ""
    curr = ""
    maxProduct = 0
    product = 1
    for i in range(n):
        product *= value(strr[i])
        curr += strr[i]
        if (product >= maxProduct):
            maxProduct = product
            answer = curr
        if (product == 0):
            product = 1
            curr = ""
    return answer


if __name__ == '__main__':
    strr = "sdtfakdhdahdzz"
    n = len(strr)
    print(maximumProduct(strr, n))

# Expected output:
hdzz
# sum of minimum and the maximum difference between two given strings | function to find the sum of the minimum and the maximum difference between two given strings ; variables to store the minimum difference and the maximum difference ; iterate through the length of the as both the given strings are of the same length ; for the maximum difference , we can replace " + " in both the strings with different char ; for the minimum difference , we can replace " + " in both the strings with the same char ; 
def solve(a, b):
    l = len(a)
    min = 0
    max = 0
    for i in range(l):
        if (a[i] == '+' or b[i] == '+' or a[i] != b[i]):
            max += 1
        if (a[i] != '+' and b[i] != '+' and a[i] != b[i]):
            min += 1
    print(min + max)


if __name__ == '__main__':
    s1 = "a+c"
    s2 = "++b"
    solve(s1, s2)

# Expected output:
4
# minimum letters to be removed to make all occurrences of a given letter continuous | function to find the minimum number of deletions required to make the occurrences of the given character k continuous ; find the first occurrence of the given letter ; iterate from the first occurrence till the end of the sequence ; find the index from where the occurrence of the character is not continuous ; update the answer with the number of elements between non - consecutive occurrences of the given letter ; update the count for all letters which are not equal to the given letter ; return the count ; 
def noOfDeletions(string, k):
    ans = 0
    cnt = 0
    pos = 0
    while (pos < len(string) and string[pos] != k):
        pos += 1
    i = pos
    while (i < len(string)):
        while (i < len(string) and string[i] == k):
            i = i + 1
        ans = ans + cnt
        cnt = 0
        while (i < len(string) and string[i] != k):
            i = i + 1
            cnt = cnt + 1
    return ans


if __name__ == "__main__":
    str1 = "ababababa"
    k1 = 'a'
    print(noOfDeletions(str1, k1))
    str2 = "kprkkoinkopt"
    k2 = 'k'
    print(noOfDeletions(str2, k2))

# Expected output:
4
5
# check whether an array of strings can correspond to a particular number x | function to find the maximum base possible for the number n ; function to find the decimal equivalent of the number ; condition to check if the number is convertible to another base ; function to check that the array can correspond to a number x ; counter to count the numbers those are convertible to x ; loop to iterate over the array ; convert the current string to every base for checking whether it will correspond to x from any base ; condition to check if every number of the array can be converted to x ; 
def val(c):
    if (c >= '0' and c <= '9'):
        return int(c)
    else:
        return c - 'A' + 10


def toDeci(strr, base):
    lenn = len(strr)
    power = 1
    num = 0
    for i in range(lenn - 1, -1, -1):
        if (val(strr[i]) >= base):
            return -1
        num += val(strr[i]) * power
        power = power * base
    return num


def checkCorrespond(strr, x):
    counter = 0
    n = len(strr)
    for i in range(n):
        for j in range(2, 37):
            if (toDeci(strr[i], j) == x):
                counter += 1
                break
    if (counter == n):
        print("YES")
    else:
        print("NO")


x = 16
strr = ["10000", "20", "16"]
checkCorrespond(strr, x)

# Expected output:
YES
# count of same length strings that exists lexicographically in between two given strings | function to find the count of strings less than given string lexicographically ; find length of string s ; looping over the string characters and finding strings less than that character ; function to find the count of same length strings that exists lexicographically in between two given strings ; count string less than s1 ; count string less than s2 ; total strings between s1 and s2 would be difference between the counts - 1 ; if s1 is lexicographically greater than s2 then return 0 , otherwise return the value of totalstring ; 
def LexicoLesserStrings(s):
    count = 0
    length = len(s)
    for i in range(length):
        count += ((ord(s[i]) - ord('a')) * pow(26, length - i - 1))
    return count


def countString(S1, S2):
    countS1 = LexicoLesserStrings(S1)
    countS2 = LexicoLesserStrings(S2)
    totalString = countS2 - countS1 - 1
    return (0 if totalString < 0 else totalString)


S1 = "cda"
S2 = "cef"
print(countString(S1, S2))

# Expected output:
30
# longest subsequence of a string containing only vowels | function to check whether a character is vowel or not ; returns true if x is vowel ; function to find the longest subsequence which contain all vowels ; length of the string ; iterating through the string ; checking if the character is a vowel or not ; if it is a vowel , then add it to the final string ; 
def isVowel(x):
    return (x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u')


def longestVowelSubsequence(str):
    answer = ""
    n = len(str)
    for i in range(n):
        if (isVowel(str[i])):
            answer += str[i]
    return answer


str = "geeksforgeeks"
print(longestVowelSubsequence(str))

# Expected output:
eeoee
# maximum repeated frequency of characters in a given string | function to find the maximum repeated frequency of the characters in the given string ; hash - array to store the frequency of characters ; loop to find the frequency of the characters ; hash map to store the occurrence of frequencies of characters ; loop to find the maximum repeated frequency from hash - map ; 
def findMaxFrequency(s):
    arr = [0] * 26
    for i in range(len(s)):
        arr[ord(s[i]) - ord('a')] += 1
    hash = {}
    for i in range(26):
        if (arr[i] != 0):
            if arr[i]not in hash:
                hash[arr[i]] = 0
            hash[arr[i]] += 1
    max_count = 0
    res = -1
    for i in hash:
        if (max_count < hash[i]):
            res = i
            max_count = hash[i]
    print("Frequency", res, "is repeated", max_count, "times")


s = "geeksgeeks"
findMaxFrequency(s)

# Expected output:
Frequency 2 is repeated 3 times
# generate string with hamming distance as half of the hamming distance between strings a and b | function to find the required string ; find the hamming distance between a and b ; if distance is odd , then resultant string is not possible ; make the resultant string ; to store the final string ; pick k characters from each string ; pick k characters from string b ; pick k characters from string a ; append the res characters from string to the resultant string ; print the resultant string ; 
def findString(A, B):
    dist = 0
    for i in range(len(A)):
        if (A[i] != B[i]):
            dist += 1
    if (dist & 1):
        print("Not Possible")
    else:
        res = ""
        K = dist // 2
        for i in range(len(A)):
            if (A[i] != B[i] and K > 0):
                res += B[i]
                K -= 1
            elif (A[i] != B[i]):
                res += A[i]
            else:
                res += A[i]
        print(res)


if __name__ == "__main__":
    A = "1001010"
    B = "0101010"
    findString(A, B)

# Expected output:
0001010
# longest suffix such that occurrence of each character is less than n after deleting atmost k characters | function to find the maximum length suffix in the string ; length of the string ; map to store the number of occurrence of character ; loop to iterate string from the last character ; condition to check if the occurrence of each character is less than given number ; condition when character cannot be deleted ; longest suffix ; 
def maximumSuffix(s, n, k):
    i = len(s) - 1
    arr = [0 for i in range(26)]
    suffix = ""
    while (i > -1):
        index = ord(s[i]) - ord('a')
        if (arr[index] < n):
            arr[index] += 1
            suffix += s[i]
            i -= 1
            continue
        if (k == 0):
            break
        k -= 1
        i -= 1
    suffix = suffix[::-1]
    print(suffix)


if __name__ == '__main__':
    str = "iahagafedcba"
    n = 1
    k = 2
    maximumSuffix(str, n, k)

# Expected output:
hgfedcba
# xor of two binary strings | function to find the xor of the two binary strings ; loop to iterate over the binary strings ; if the character matches ; 
def xor(a, b, n):
    ans = ""
    for i in range(n):
        if (a[i] == b[i]):
            ans += "0"
        else:
            ans += "1"
    return ans


if __name__ == "__main__":
    a = "1010"
    b = "1101"
    n = len(a)
    c = xor(a, b, n)
    print(c)

# Expected output:
0111
# find kth largest string from the permutations of the string with two characters | function to print the kth largest string ; loop to iterate through series ; total takes the position of second y ; i takes the position of first y ; calculating first y position ; calculating second y position from first y ; print all x before first y ; print first y ; print all x between first y and second y ; print second y ; print x which occur after second y ; 
def kthString(n, k):
    total = 0
    i = 1
    while (total < k):
        total = total + n - i
        i += 1
    first_y_position = i - 1
    second_y_position = k - (total - n + first_y_position)
    for j in range(1, first_y_position, 1):
        print("x", end="")
    print("y", end="")
    j = first_y_position + 1
    while (second_y_position > 1):
        print("x", end="")
        second_y_position -= 1
        j += 1
    print("y", end="")
    while (j < n):
        print("x")
        j += 1


if __name__ == '__main__':
    n = 5
    k = 7
    kthString(n, k)

# Expected output:
xyxxy
# largest and smallest n | function to return the largest n - digit number in octal number system ; append '7' n times ; function to return the smallest n - digit number in octal number system ; append '0' ( n - 1 ) times to 1 ; function to print the largest and smallest n - digit octal number ; 
def findLargest(N):
    largest = strings(N, '7')
    return largest


def findSmallest(N):
    smallest = "1" + strings((N - 1), '0')
    return smallest


def strings(N, c):
    temp = ""
    for i in range(N):
        temp += c
    return temp


def printLargestSmallest(N):
    print("Largest: ", findLargest(N))
    print("Smallest: ", findSmallest(N))


if __name__ == '__main__':
    N = 4
    printLargestSmallest(N)

# Expected output:
Largest:  7777
Smallest:  1000