giulio98/xlcost-single-prompt huggingface dataset:
# decode the string encoded with the given algorithm | function to decode and print the original string ; to store the decoded string ; getting the mid element ; storing the first element of the string at the median position ; if the length is even then store the second element also ; k represents the number of characters that are already stored in the c [ ] ; if string length is odd ; if it is even ; print the decoded string ; 
def decodeStr(str, len):
    c = [""for i in range(len)]
    pos = 1
    if (len % 2 == 1):
        med = int(len / 2)
    else:
        med = int(len / 2 - 1)
    c[med] = str[0]
    if (len % 2 == 0):
        c[med + 1] = str[1]
    if (len & 1):
        k = 1
    else:
        k = 2
    for i in range(k, len, 2):
        c[med - pos] = str[i]
        if (len % 2 == 1):
            c[med + pos] = str[i + 1]
        else:
            c[med + pos + 1] = str[i + 1]
        pos += 1
    print(*c, sep="")


str = "ofrsgkeeeekgs"
len = len(str)
decodeStr(str, len)

# Expected output:
geeksforgeeks
# count of distinct characters in a substring by given range for q queries | python3 program for naive approach ; counter to count distinct char ; initializing frequency array to count characters as the appear in substring s [ l : r ] ; iterating over s [ l ] to s [ r ] ; incrementing the count of s [ i ] character in frequency array ; if frequency of any character is > 0 then increment the counter ; 
def findCount(s, L, R):
    distinct = 0
    frequency = [0 for i in range(26)]
    for i in range(L, R + 1, 1):
        frequency[ord(s[i]) - ord('a')] += 1
    for i in range(26):
        if (frequency[i] > 0):
            distinct += 1
    print(distinct)


if __name__ == '__main__':
    s = "geeksforgeeksisacomputerscienceportal"
    queries = 3
    Q = [[0, 10], [15, 18], [12, 20]]
    for i in range(queries):
        findCount(s, Q[i][0], Q[i][1])

# Expected output:
7
4
8
# string obtained by reversing and complementing a binary string k times | function to perform k operations upon the string and find modified string ; number of reverse operations ; number of complement operations ; if rev is odd parity ; if complement is odd parity ; complementing each position ; return the modified string ; 
def ReverseComplement(s, n, k):
    rev = (k + 1) // 2
    complement = k - rev
    if (rev % 2):
        s = s[::-1]
    if (complement % 2):
        for i in range(n):
            if (s[i] == '0'):
                s[i] = '1'
            else:
                s[i] = '0'
    return s


if __name__ == '__main__':
    str1 = "10011"
    k = 5
    n = len(str1)
    print(ReverseComplement(str1, n, k))

# Expected output:
11001
# check if any permutation of string is a k times repeated string | function to check that permutation of the given string is a k times repeating string ; if length of string is not divisible by k ; frequency array ; initially frequency of each character is 0 ; computing the frequency of each character in the string ; loop to check that frequency of every character of the string is divisible by k ; 
def repeatingString(s, n, k):
    if (n % k != 0):
        return False
    frequency = [0 for i in range(123)]
    for i in range(123):
        frequency[i] = 0
    for i in range(n):
        frequency[s[i]] += 1
    repeat = n // k
    for i in range(123):
        if (frequency[i] % repeat != 0):
            return False
    return True


if __name__ == '__main__':
    s = "abcdcba"
    n = len(s)
    k = 3
    if (repeatingString(s, n, k)):
        print("Yes")
    else:
        print("No")

# Expected output:
No
# find the last two missing digits of the given phone number | function to find the last two digits of the number and print the complete number ; sum of the first eight digits of the number ; if sum < 10 , then the two digits are '0' and the value of sum ; if sum > 10 , then the two digits are the value of sum ; 
def findPhoneNumber(n):
    temp = n
    sum = 0
    while (temp != 0):
        sum += temp % 10
        temp = temp // 10
    if (sum < 10):
        print(n, "0", sum)
    else:
        n = str(n)
        sum = str(sum)
        n += sum
        print(n)


if __name__ == '__main__':
    n = 98765432
    findPhoneNumber(n)

# Expected output:
9876543244
# number of ways to split a binary number such that every part is divisible by 2 | function to return the required count ; if the splitting is not possible ; to store the count of zeroes ; counting the number of zeroes ; return the final answer ; 
def cntSplits(s):
    if (s[len(s) - 1] == '1'):
        return 0
    c_zero = 0
    for i in range(len(s)):
        c_zero += (s[i] == '0')
    return int(pow(2, c_zero - 1))


if __name__ == "__main__":
    s = "10010"
    print(cntSplits(s))

# Expected output:
4
# count number of substrings of a string consisting of same characters | function to return the number of substrings of same characters ; size of the string ; initialize count to 1 ; initialize left to 0 and right to 1 to traverse the string ; checking if consecutive characters are same and increment the count ; when we encounter a different characters ; increment the result ; to repeat the whole process set left equals right and count variable to 1 ; store the final value of result ; 
def findNumbers(s):
    n = len(s)
    count = 1
    result = 0
    left = 0
    right = 1
    while (right < n):
        if (s[left] == s[right]):
            count += 1
        else:
            result += count * (count + 1) // 2
            left = right
            count = 1
        right += 1
    result += count * (count + 1) // 2
    print(result)


s = "bbbcbb"
findNumbers(s)

# Expected output:
10
# program to duplicate vowels in string | function to check for the vowel ; function to get the resultant string with vowels duplicated ; another to store the resultant string ; loop to check for each character ; 
def isVowel(ch):
    ch = ch .upper()
    if (ch == 'A' or ch == 'E' or ch == 'I' or ch == 'O' or ch == 'U'):
        return True
    else:
        return False


def duplicateVowels(S):
    t = len(S)
    res = ""
    for i in range(t):
        if (isVowel(S[i])):
            res += S[i]
        res += S[i]
    return res


S = "helloworld"
print("Original String: ", S)
res = duplicateVowels(S)
print("String with Vowels duplicated: ", res)

# Expected output:
Original String:  helloworld
String with Vowels duplicated:  heelloowoorld
# convert a string to an integer using recursion | recursive function to convert string to integer ; if the number represented as a string contains only a single digit then returns its value ; recursive call for the sub - string starting at the second character ; first digit of the number ; first digit multiplied by the appropriate power of 10 and then add the recursive result for example , xy = ( ( x * 10 ) + y ) ; 
def stringToInt(str):
    if (len(str) == 1):
        return ord(str[0]) - ord('0')
    y = stringToInt(str[1:])
    x = ord(str[0]) - ord('0')
    x = x * (10 ** (len(str) - 1)) + y
    return int(x)


if __name__ == '__main__':
    str = "1235"
    print(stringToInt(str))

# Expected output:
1235
# longest subsequence with at least one character appearing in every string | python3 implementation of the approach ; function to return the length of the longest sub - sequence with at least one common character in every string ; count [ 0 ] will store the number of strings which contain ' a ' , count [ 1 ] will store the number of strings which contain ' b ' and so on . . ; for every string ; hash array to set which character is present in the current string ; if current character appears in the string then update its count ; 

MAX = 26


def largestSubSeq(arr, n):
    count = [0] * MAX
    for i in range(n):
        string = arr[i]
        _hash = [False] * MAX
        for j in range(len(string)):
            _hash[ord(string[j]) - ord('a')] = True
        for j in range(MAX):
            if _hash[j]:
                count[j] += 1
    return max(count)


if __name__ == "__main__":
    arr = ["ab", "bc", "de"]
    n = len(arr)
    print(largestSubSeq(arr, n))

# Expected output:
2
# generate number with given operation and check if it is palindrome | function that returns true if str is a palindrome ; function that returns true if the generated string is a palindrome ; sub contains n as a string ; calculate the sum of the digits ; repeat the substring until the length of the resultant string < sum ; if length of the resultant string exceeded sum then take substring from 0 to sum - 1 ; if the generated string is a palindrome ; 
def isPalindrome(s):
    l = len(s)
    for i in range(l // 2):
        if (s[i] != s[l - 1 - i]):
            return False
    return True


def createStringAndCheckPalindrome(N):
    sub = "" + chr(N)
    res_str = ""
    sum = 0
    while (N > 0):
        digit = N % 10
        sum += digit
        N = N // 10
    while (len(res_str) < sum):
        res_str += sub
    if (len(res_str) > sum):
        res_str = res_str[0:sum]
    if (isPalindrome(res_str)):
        return True
    return False


if __name__ == "__main__":
    N = 10101
    if (createStringAndCheckPalindrome(N)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# minimize the length of string by removing occurrence of only one character | function to find the minimum length ; count the frequency of each alphabet ; find the alphabets with maximum frequency ; subtract the frequency of character from length of string ; 
def minimumLength(s):
    maxOcc = 0
    n = len(s)
    arr = [0] * 26
    for i in range(n):
        arr[ord(s[i]) - ord('a')] += 1
    for i in range(26):
        if arr[i] > maxOcc:
            maxOcc = arr[i]
    return n - maxOcc


if __name__ == "__main__":
    str = "afddewqd"
    print(minimumLength(str))

# Expected output:
5
# remove all characters other than alphabets from string | function to remove characters and pr new string ; finding the character whose ascii value fall under this range ; erase function to erase the character ; 
def removeSpecialCharacter(s):
    i = 0
    while i < len(s):
        if (ord(s[i]) < ord('A') or ord(s[i]) > ord('Z')
                and ord(s[i]) < ord('a') or ord(s[i]) > ord('z')):
            del s[i]
            i -= 1
        i += 1
    print("".join(s))


if __name__ == '__main__':
    s = "$Gee*k;s..fo, r'Ge^eks?"
    s = [i for i in s]
    removeSpecialCharacter(s)

# Expected output:
GeeksforGeeks
# remove all characters other than alphabets from string | function to remove special characters and store it in another variable ; store only valid characters ; 
def removeSpecialCharacter(s):
    t = ""
    for i in s:
        if (i >= 'A' and i <= 'Z') or (i >= 'a' and i <= 'z'):
            t += i
    print(t)


s = "$Gee*k;s..fo, r'Ge^eks?"
removeSpecialCharacter(s)

# Expected output:
GeeksforGeeks
# find repeated character present first in a string | python3 program to find the first character that is repeated ; this is o ( n ^ 2 ) method ; 
def findRepeatFirstN2(s):
    p = -1
    for i in range(len(s)):
        for j in range(i + 1, len(s)):
            if (s[i] == s[j]):
                p = i
                break
        if (p != -1):
            break
    return p


if __name__ == "__main__":
    str = "geeksforgeeks"
    pos = findRepeatFirstN2(str)
    if (pos == -1):
        print("Not found")
    else:
        print(str[pos])

# Expected output:
g
# print characters and their frequencies in order of occurrence | python3 implementation to print the characters and frequencies in order of its occurrence ; store all characters and their frequencies in dictionary ; print characters and their frequencies in same order of their appearance ; print only if this character is not printed before . ; 
def prCharWithFreq(str):
    d = {}
    for i in str:
        if i in d:
            d[i] += 1
        else:
            d[i] = 1
    for i in str:
        if d[i] != 0:
            print("{}{}".format(i, d[i]), end=" ")
            d[i] = 0


if __name__ == "__main__":

    str = "geeksforgeeks"
    prCharWithFreq(str)

# Expected output:
g2 e4 k2 s2 f1 o1 r1
# count number of strings ( made of r , g and b ) using given combination | function to calculate number of strings ; store factorial of numbers up to n for further computation ; find the remaining values to be added ; make all possible combinations of r , b and g for the remaining value ; compute permutation of each combination one by one and add them . ; return total no . of strings / permutation ; 
def possibleStrings(n, r, b, g):
    fact = [0 for i in range(n + 1)]
    fact[0] = 1
    for i in range(1, n + 1, 1):
        fact[i] = fact[i - 1] * i
    left = n - (r + g + b)
    sum = 0
    for i in range(0, left + 1, 1):
        for j in range(0, left - i + 1, 1):
            k = left - (i + j)
            sum = (sum + fact[n] / (fact[i + r] * fact[j + b] * fact[k + g]))
    return sum


if __name__ == '__main__':
    n = 4
    r = 2
    b = 0
    g = 1
    print(int(possibleStrings(n, r, b, g)))

# Expected output:
22
# remove minimum number of characters so that two strings become anagram | python 3 program to find minimum number of characters to be removed to make two strings anagram . ; function to calculate minimum numbers of characters to be removed to make two strings anagram ; make hash array for both string and calculate frequency of each character ; count frequency of each character in first string ; count frequency of each character in second string ; traverse count arrays to find number of characters to be removed ; 

CHARS = 26


def remAnagram(str1, str2):
    count1 = [0] * CHARS
    count2 = [0] * CHARS
    i = 0
    while i < len(str1):
        count1[ord(str1[i]) - ord('a')] += 1
        i += 1
    i = 0
    while i < len(str2):
        count2[ord(str2[i]) - ord('a')] += 1
        i += 1
    result = 0
    for i in range(26):
        result += abs(count1[i] - count2[i])
    return result


if __name__ == "__main__":
    str1 = "bcadeh"
    str2 = "hea"
    print(remAnagram(str1, str2))

# Expected output:
3
# check if a string has all characters with same frequency with one variation allowed | assuming only lower case characters ; to check a string s can be converted to a valid string by removing less than or equal to one character . ; freq [ ] : stores the frequency of each character of a string ; find first character with non - zero frequency ; find a character with frequency different from freq1 . ; if we find a third non - zero frequency or count of both frequencies become more than 1 , then return false ; if we find a third non - zero freq ; if counts of both frequencies is more than 1 ; return true if we reach here ; 

CHARS = 26


def isValidString(str):
    freq = [0] * CHARS
    for i in range(len(str)):
        freq[ord(str[i]) - ord('a')] += 1
    freq1 = 0
    count_freq1 = 0
    for i in range(CHARS):
        if (freq[i] != 0):
            freq1 = freq[i]
            count_freq1 = 1
            break
    freq2 = 0
    count_freq2 = 0
    for j in range(i + 1, CHARS):
        if (freq[j] != 0):
            if (freq[j] == freq1):
                count_freq1 += 1
            else:
                count_freq2 = 1
                freq2 = freq[j]
                break
    for k in range(j + 1, CHARS):
        if (freq[k] != 0):
            if (freq[k] == freq1):
                count_freq1 += 1
            if (freq[k] == freq2):
                count_freq2 += 1
            else:
                return False
        if (count_freq1 > 1 and count_freq2 > 1):
            return False
    return True


if __name__ == "__main__":
    str = "abcbc"
    if (isValidString(str)):
        print("YES")
    else:
        print("NO")

# Expected output:
YES
# check if a string has all characters with same frequency with one variation allowed | to check a string s can be converted to a variation string ; run loop form 0 to length of string ; declaration of variables ; if first is true than countofval1 increase ; if second is true than countofval2 increase ; 
def checkForVariation(strr):
    if (len(strr) == 0):
        return True
    mapp = {}
    for i in range(len(strr)):
        if strr[i] in mapp:
            mapp[strr[i]] += 1
        else:
            mapp[strr[i]] = 1
    first = True
    second = True
    val1 = 0
    val2 = 0
    countOfVal1 = 0
    countOfVal2 = 0
    for itr in mapp:
        i = itr
        if (first):
            val1 = i
            first = False
            countOfVal1 += 1
            continue
        if (i == val1):
            countOfVal1 += 1
            continue
        if (second):
            val2 = i
            countOfVal2 += 1
            second = False
            continue
        if (i == val2):
            countOfVal2 += 1
            continue
    if (countOfVal1 > 1 and countOfVal2 > 1):
        return False
    else:
        return True


print(checkForVariation("abcbc"))

# Expected output:
True
# pairs of complete strings in two sets of strings | returns count of complete pairs from set [ 0. . n - 1 ] and set2 [ 0. . m - 1 ] ; con_s1 [ i ] is going to store an integer whose set bits represent presence / absence of characters in set1 [ i ] . similarly con_s2 [ i ] is going to store an integer whose set bits represent presence / absence of characters in set2 [ i ] ; process all strings in set1 [ ] ; initializing all bits to 0 ; setting the ascii code of char s [ i ] [ j ] to 1 in the compressed integer . ; process all strings in set2 [ ] ; initializing all bits to 0 ; setting the ascii code of char s [ i ] [ j ] to 1 in the compressed integer . ; assigning a variable whose all 26 ( 0. . 25 ) bits are set to 1 ; now consider every pair of integer in con_s1 [ ] and con_s2 [ ] and check if the pair is complete . ; if all bits are set , the strings are complete ! ; 
def countCompletePairs(set1, set2, n, m):
    result = 0
    con_s1, con_s2 = [0] * n, [0] * m
    for i in range(n):
        con_s1[i] = 0
        for j in range(len(set1[i])):
            con_s1[i] = con_s1[i] | (1 << (ord(set1[i][j]) - ord('a')))
    for i in range(m):
        con_s2[i] = 0
        for j in range(len(set2[i])):
            con_s2[i] = con_s2[i] | (1 << (ord(set2[i][j]) - ord('a')))
    complete = (1 << 26) - 1
    for i in range(n):
        for j in range(m):
            if ((con_s1[i] | con_s2[j]) == complete):
                result += 1
    return result


if __name__ == '__main__':
    set1 = ["abcdefgh", "geeksforgeeks", "lmnopqrst", "abc"]
    set2 = [
        "ijklmnopqrstuvwxyz",
        "abcdefghijklmnopqrstuvwxyz",
        "defghijklmnopqrstuvwxyz"]
    n = len(set1)
    m = len(set2)
    print(countCompletePairs(set1, set2, n, m))

# Expected output:
7
# find all strings that match specific pattern in a dictionary | function to encode given string ; for each character in given string ; if the character is occurring for the first time , assign next unique number to that char ; append the number associated with current character into the output string ; function to print all the strings that match the given pattern where every character in the pattern is uniquely mapped to a character in the dictionary ; len is length of the pattern ; encode the string ; for each word in the dictionary array ; if size of pattern is same as size of current dictionary word and both pattern and the word has same hash , print the word ; 
def encodeString(Str):
    map = {}
    res = ""
    i = 0
    for ch in Str:
        if ch not in map:
            map[ch] = i
            i += 1
        res += str(map[ch])
    return res


def findMatchedWords(dict, pattern):
    Len = len(pattern)
    hash = encodeString(pattern)
    for word in dict:
        if (len(word) == Len and encodeString(word) == hash):
            print(word, end=" ")


dict = ["abb", "abc", "xyz", "xyy"]
pattern = "foo"
findMatchedWords(dict, pattern)

# Expected output:
abb xyy
# find all strings that match specific pattern in a dictionary | python3 program to print all the strings that match the given pattern where every character in the pattern is uniquely mapped to a character in the dictionary ; function to print all the strings that match the given pattern where every character in the pattern is uniquely mapped to a character in the dictionary ; len is length of the pattern ; for each word in the dictionary ; 
def check(pattern, word):
    if (len(pattern) != len(word)):
        return False
    ch = [0 for i in range(128)]
    Len = len(word)
    for i in range(Len):
        if (ch[ord(pattern[i])] == 0):
            ch[ord(pattern[i])] = word[i]
        elif (ch[ord(pattern[i])] != word[i]):
            return False
    return True


def findMatchedWords(Dict, pattern):
    Len = len(pattern)
    for word in range(len(Dict) - 1, -1, -1):
        if (check(pattern, Dict[word])):
            print(Dict[word], end=" ")


Dict = ["abb", "abc", "xyz", "xyy"]
pattern = "foo"
findMatchedWords(Dict, pattern)

# Expected output:
xyy abb
# reverse words in a given string | reverse the string ; check if number of words is even ; find the middle word ; starting from the middle start swapping words at jth position and l - 1 - j position ; check if number of words is odd ; find the middle word ; starting from the middle start swapping the words at jth position and l - 1 - j position ; return the reversed sentence ; 
def RevString(s, l):
    if l % 2 == 0:
        j = int(l / 2)
        while (j <= l - 1):
            s[j], s[l - j - 1] = s[l - j - 1], s[j]
            j += 1
    else:
        j = int(l / 2 + 1)
        while (j <= l - 1):
            s[j], s[l - 1 - j] = s[l - j - 1], s[j]
            j += 1
        return s


s = 'getting good at coding needs a lot of practice'
string = s .split(' ')
string = RevString(string, len(string))
print(" ".join(string))

# Expected output:
practice of lot a needs coding at good getting
# print path from root to all nodes in a complete binary tree | function to print path of all the nodes nth node represent as given node kth node represents as left and right node ; base condition if kth node value is greater then nth node then its means kth node is not valid so we not store it into the res simply we just return ; storing node into res ; print the path from root to node ; store left path of a tree so for left we will go node ( kthnode * 2 ) ; right path of a tree and for right we will go node ( kthnode * 2 + 1 ) ; function to print path from root to all of the nodes ; res is for store the path from root to particulate node ; print path from root to all node . third argument 1 because of we have to consider root node is 1 ; 
def printPath(res, nThNode, kThNode):
    if kThNode > nThNode:
        return
    res .append(kThNode)
    for i in range(0, len(res)):
        print(res[i], end=" ")
    print()
    printPath(res[:], nThNode, kThNode * 2)
    printPath(res[:], nThNode, kThNode * 2 + 1)


def printPathToCoverAllNodeUtil(nThNode):
    res = []
    printPath(res, nThNode, 1)


if __name__ == "__main__":
    nThNode = 7
    printPathToCoverAllNodeUtil(nThNode)

# Expected output:
1 
1 2 
1 2 4 
1 2 5 
1 3 
1 3 6 
1 3 7
# maximum number of region in which n non | function to find the maximum number of regions on a plane ; print the maximum number of regions ; 
def maxRegions(n):
    num = n * (n + 1) // 2 + 1
    print(num)


n = 10
maxRegions(n)

# Expected output:
56
# check whether jigsaw puzzle solveable or not | function to check if the jigsaw puzzle is solveable or not ; base case ; by placing the blank tabs as a chain ; 
def checkSolveable(n, m):
    if n == 1 or m == 1:
        print("YES")
    elif m == 2 and n == 2:
        print("YES")
    else:
        print("NO")


if __name__ == "__main__":
    n = 1
    m = 3
    checkSolveable(n, m)

# Expected output:
YES
# check if it is possible to reach ( x , y ) from ( 1 , 0 ) by given steps | function to find the gcd of two numbers a and b ; base case ; recursively find the gcd ; function to check if ( x , y ) can be reached from ( 1 , 0 ) from given moves ; if gcd is 1 , then pr " yes " ; 
def GCD(a, b):
    if (b == 0):
        return a
    else:
        return GCD(b, a % b)


def check(x, y):
    if (GCD(x, y) == 1):
        print("Yes")
    else:
        print("No")


if __name__ == '__main__':
    X = 2
    Y = 7
    check(X, Y)

# Expected output:
Yes