giulio98/xlcost-single-prompt huggingface dataset:
# substrings starting with vowel and ending with consonants and vice versa | returns true if ch is vowel ; function to check consonant ; in case of empty string , we can 't fullfill the  required condition, hence we return ans as 0. ; co [ i ] is going to store counts of consonants from str [ len - 1 ] to str [ i ] . vo [ i ] is going to store counts of vowels from str [ len - 1 ] to str [ i ] . ; counting consonants and vowels from end of string . ; now we traverse string from beginning ; if vowel , then count of substrings starting with str [ i ] is equal to count of consonants after it . ; if consonant , then count of substrings starting with str [ i ] is equal to count of vowels after it . ; 
def isVowel(ch):
    return (ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u')


def isCons(ch):
    return (ch != 'a' and ch != 'e' and ch != 'i' and ch != 'o' and ch != 'u')


def countSpecial(str):
    lent = len(str)
    if lent == 0:
        return 0
    co = []
    vo = []
    for i in range(0, lent + 1):
        co .append(0)
    for i in range(0, lent + 1):
        vo .append(0)
    if isCons(str[lent - 1]) == 1:
        co[lent - 1] = 1
    else:
        vo[lent - 1] = 1
    for i in range(lent - 2, -1, -1):
        if isCons(str[i]) == 1:
            co[i] = co[i + 1] + 1
            vo[i] = vo[i + 1]
        else:
            co[i] = co[i + 1]
            vo[i] = vo[i + 1] + 1
    ans = 0
    for i in range(lent):
        if isVowel(str[i]):
            ans = ans + co[i + 1]
        else:
            ans = ans + vo[i + 1]
    return ans


str = "adceba"
print(countSpecial(str))

# Expected output:
9
# convert the string into palindrome string by changing only one character | function to check if it is possible to convert the string into palindrome ; counting number of characters that should be changed . ; if count of changes is less than or equal to 1 ; 
def checkPalindrome(str):
    n = len(str)
    count = 0
    for i in range(0, int(n / 2)):
        if (str[i] != str[n - i - 1]):
            count = count + 1
    if (count <= 1):
        return True
    else:
        return False


str = "abccaa"
if (checkPalindrome(str)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# number of substrings with odd decimal value in a binary string | python program to count substrings with odd decimal value ; function to count number of substrings with odd decimal representation ; auxiliary array to store count of 1 's before ith index ; store count of 1 's before  i-th index ; variable to store answer ; traverse the string reversely to calculate number of odd substrings before i - th index ; 

import math


def countSubstr(s):
    n = len(s)
    auxArr = [0 for i in range(n)]
    if (s[0] == '1'):
        auxArr[0] = 1
    for i in range(0, n):
        if (s[i] == '1'):
            auxArr[i] = auxArr[i - 1] + 1
        else:
            auxArr[i] = auxArr[i - 1]
        count = 0
    for i in range(n - 1, -1, -1):
        if (s[i] == '1'):
            count += auxArr[i]
    return count


s = "1101"
print(countSubstr(s))

# Expected output:
6
# find the starting indices of the substrings in string ( s ) which is made by concatenating all words from a list ( l ) | returns an integer vector consisting of starting indices of substrings present inside the string s ; number of a characters of a word in list l . ; number of words present inside list l . ; total characters present in list l . ; resultant vector which stores indices . ; if the total number of characters in list l is more than length of string s itself . ; map stores the words present in list l against it 's occurrences inside list l ; traverse the substring ; extract the word ; if word not found or if frequency of current word is more than required simply break . ; else decrement the count of word from hash_map ; store the starting index of that substring when all the words in the list are in substring ; 
def findSubStringIndices(s, L):
    size_word = len(L[0])
    word_count = len(L)
    size_L = size_word * word_count
    res = []
    if size_L > len(s):
        return res
    hash_map = dict()
    for i in range(word_count):
        if L[i] in hash_map:
            hash_map[L[i]] += 1
        else:
            hash_map[L[i]] = 1
    for i in range(0, len(s) - size_L + 1, 1):
        temp_hash_map = hash_map .copy()
        j = i
        count = word_count
        while j < i + size_L:
            word = s[j:j + size_word]
            if (word not in hash_map or temp_hash_map[word] == 0):
                break
            else:
                temp_hash_map[word] -= 1
                count -= 1
            j += size_word
        if count == 0:
            res .append(i)
    return res


if __name__ == "__main__":
    s = "barfoothefoobarman"
    L = ["foo", "bar"]
    indices = findSubStringIndices(s, L)
    print(*indices)

# Expected output:
0 9
# check whether second string can be formed from characters of first string | python program to check whether second string can be formed from first string ; create a count array and count frequencies characters in s1 ; now traverse through str2 to check if every character has enough counts ; 
def canMakeStr2(s1, s2):
    count = {s1[i]: 0 for i in range(len(s1))}
    for i in range(len(s1)):
        count[s1[i]] += 1
    for i in range(len(s2)):
        if (count .get(s2[i]) is None or count[s2[i]] == 0):
            return False
        count[s2[i]] -= 1
    return True


s1 = "geekforgeeks"
s2 = "for"
if canMakeStr2(s1, s2):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# position of robot after given movements | function to find final position of robot after the complete movement ; traverse the instruction string 'move ; for each movement increment its respective counter ; required final position of robot ; 
def finalPosition(move):
    l = len(move)
    countUp, countDown = 0, 0
    countLeft, countRight = 0, 0
    for i in range(l):
        if (move[i] == 'U '):
            countUp += 1
        elif (move[i] == 'D '):
            countDown += 1
        elif (move[i] == 'L '):
            countLeft += 1
        elif (move[i] == 'R '):
            countRight += 1
    print("Final Position: (", (countRight-countLeft), ", ", (countUp-countDown), ")")


if __name__ == '__main__':
    move = "UDDLLRUUUDUURUDDUULLDRRRR"
    finalPosition(move)

# Expected output:
Final Position: ( 0 ,  0 )
# length of longest balanced parentheses prefix | function to return the length of longest balanced parentheses prefix . ; traversing the string . ; if open bracket add 1 to sum . ; if closed bracket subtract 1 from sum ; if first bracket is closing bracket then this condition would help ; if sum is 0 , store the index value . ; 
def maxbalancedprefix(str, n):
    _sum = 0
    maxi = 0
    for i in range(n):
        if str[i] == '(':
            _sum += 1
        else:
            _sum -= 1
        if _sum < 0:
            break
        if _sum == 0:
            maxi = i + 1
    return maxi


str = '((()())())(('
n = len(str)
print(maxbalancedprefix(str, n))

# Expected output:
10
# minimum cost to convert string into palindrome | function to return cost ; length of string ; iterate from both sides of string . if not equal , a cost will be there ; 
def cost(st):
    l = len(st)
    res = 0
    j = l - 1
    i = 0
    while (i < j):
        if (st[i] != st[j]):
            res += (min(ord(st[i]), ord(st[j])) - ord('a') + 1)
        i = i + 1
        j = j - 1
    return res


st = "abcdef"
print(cost(st))

# Expected output:
6
# encoding a word into pig latin | python program to encode a word to a pig latin . ; the index of the first vowel is stored . ; pig latin is possible only if vowels is present ; take all characters after index ( including index ) . append all characters which are before index . finally append " ay " ; 
def isVowel(c):
    return (c == 'A' or c == 'E' or c == 'I' or
            c == 'O' or c == 'U' or c == 'a' or
            c == 'e' or c == 'i' or c == 'o' or
            c == 'u')


def pigLatin(s):
    length = len(s)
    index = -1
    for i in range(length):
        if (isVowel(s[i])):
            index = i
            break
    if (index == -1):
        return "-1"
    return s[index:] + s[0:index] + "ay"


str = pigLatin("graphic")
if (str == "-1"):
    print("No vowels found. Pig Latin not possible")
else:
    print(str)

# Expected output:
aphicgray
# possibility of a word from a given set of characters | python 3 program to check if a query string is present is given set . ; count occurrences of all characters in s . ; check if number of occurrences of every character in q is less than or equal to that in s . ; 

MAX_CHAR = 256


def isPresent(s, q):
    freq = [0] * MAX_CHAR
    for i in range(0, len(s)):
        freq[ord(s[i])] += 1
    for i in range(0, len(q)):
        freq[ord(q[i])] -= 1
        if (freq[ord(q[i])] < 0):
            return False
    return True


s = "abctd"
q = "cat"
if (isPresent(s, q)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# minimum reduce operations to convert a given string into a palindrome | returns count of minimum character reduce operations to make palindrome . ; compare every character of first half with the corresponding character of second half and add difference to result . ; 
def countReduce(str):
    n = len(str)
    res = 0
    for i in range(0, int(n / 2)):
        res += abs(int(ord(str[i])) - int(ord(str[n - i - 1])))
    return res


str = "abcd"
print(countReduce(str))

# Expected output:
4
# minimal operations to make a number magical | function to calculate the minimal changes ; maximum digits that can be changed ; nested loops to generate all 6 digit numbers ; counter to count the number of change required ; if first digit is equal ; if 2 nd digit is equal ; if 3 rd digit is equal ; if 4 th digit is equal ; if 5 th digit is equal ; if 6 th digit is equal ; checks if less then the previous calculate changes ; returns the answer ; 
def calculate(s):
    ans = 6
    for i in range(10):
        for j in range(10):
            for k in range(10):
                for l in range(10):
                    for m in range(10):
                        for n in range(10):
                            if (i + j + k == l + m + n):
                                c = 0
                                if (i != ord(s[0]) - ord('0')):
                                    c += 1
                                if (j != ord(s[1]) - ord('0')):
                                    c += 1
                                if (k != ord(s[2]) - ord('0')):
                                    c += 1
                                if (l != ord(s[3]) - ord('0')):
                                    c += 1
                                if (m != ord(s[4]) - ord('0')):
                                    c += 1
                                if (n != ord(s[5]) - ord('0')):
                                    c += 1
                                if (c < ans):
                                    ans = c
    return ans


if __name__ == "__main__":
    s = "123456"
    print(calculate(s))

# Expected output:
2
# check if a two character string can be made using given words | function to check if str can be made using given words ; if str itself is present ; match first character of str with second of word and vice versa ; if both characters found . ; 
def makeAndCheckString(words, str):
    n = len(words)
    first = second = False
    for i in range(n):
        if words[i] == str:
            return True
        if str[0] == words[i][1]:
            first = True
        if str[1] == words[i][0]:
            second = True
        if first and second:
            return True
    return False


str = 'ya'
words = ['ah', 'oy', 'to', 'ha']
if makeAndCheckString(words, str):
    print('YES')
else:
    print('NO')

# Expected output:
YES
# print n | function to get the binary representation of the number n ; loop for each bit ; generate numbers in the range of ( 2 ^ n ) - 1 to 2 ^ ( n - 1 ) inclusive ; longest prefix check ; if counts of 1 is greater than counts of zero ; do sub - prefixes check ; 
def getBinaryRep(N, num_of_bits):
    r = ""
    num_of_bits -= 1
    while (num_of_bits >= 0):
        if (N & (1 << num_of_bits)):
            r += ("1")
        else:
            r += ("0")
        num_of_bits -= 1
    return r


def NBitBinary(N):
    r = []
    first = 1 << (N - 1)
    last = first * 2
    for i in range(last - 1, first - 1, -1):
        zero_cnt = 0
        one_cnt = 0
        t = i
        num_of_bits = 0
        while (t):
            if (t & 1):
                one_cnt += 1
            else:
                zero_cnt += 1
            num_of_bits += 1
            t = t >> 1
        if (one_cnt >= zero_cnt):
            all_prefix_match = True
            msk = (1 << num_of_bits) - 2
            prefix_shift = 1
            while (msk):
                prefix = ((msk & i) >> prefix_shift)
                prefix_one_cnt = 0
                prefix_zero_cnt = 0
                while (prefix):
                    if (prefix & 1):
                        prefix_one_cnt += 1
                    else:
                        prefix_zero_cnt += 1
                    prefix = prefix >> 1
                if (prefix_zero_cnt > prefix_one_cnt):
                    all_prefix_match = False
                    break
                prefix_shift += 1
                msk = msk & (msk << 1)
            if (all_prefix_match):
                r .append(getBinaryRep(i, num_of_bits))
    return r


if __name__ == "__main__":
    n = 4
    results = NBitBinary(n)
    for i in range(len(results)):
        print(results[i], end=" ")
    print()

# Expected output:
1111 1110 1101 1100 1011 1010
# find winner of an election where votes are represented as candidate names | python3 program to find winner in an election . ; we have four candidates with name as ' john ' , ' johnny ' , ' jamie ' , ' jackie ' . the votes in string array are as per the votes casted . print the name of candidates received max vote . ; insert all votes in a hashmap ; traverse through map to find the candidate with maximum votes . ; if there is a tie , pick lexicographically smaller . ; 

from collections import defaultdict


def findWinner(votes):
    mapObj = defaultdict(int)
    for st in votes:
        mapObj[st] += 1
    maxValueInMap = 0
    winner = ""
    for entry in mapObj:
        key = entry
        val = mapObj[entry]
        if (val > maxValueInMap):
            maxValueInMap = val
            winner = key
        elif (val == maxValueInMap and winner > key):
            winner = key
    print(winner)


if __name__ == "__main__":
    votes = [
        "john",
        "johnny",
        "jackie",
        "johnny",
        "john",
        "jackie",
        "jamie",
        "jamie",
        "john",
        "johnny",
        "jamie",
        "johnny",
        "john"]
    findWinner(votes)

# Expected output:
john
# luhn algorithm | returns true if given card number is valid ; we add two digits to handle cases that make two digits after doubling ; 
def checkLuhn(cardNo):
    nDigits = len(cardNo)
    nSum = 0
    isSecond = False
    for i in range(nDigits - 1, -1, -1):
        d = ord(cardNo[i]) - ord('0')
        if (isSecond):
            d = d * 2
        nSum += d // 10
        nSum += d % 10
        isSecond = not isSecond
    if (nSum % 10 == 0):
        return True
    else:
        return False


if __name__ == "__main__":
    cardNo = "79927398713"
    if (checkLuhn(cardNo)):
        print("This is a valid card")
    else:
        print("This is not a valid card")

# Expected output:
This is a valid card
# distributing all balls without repetition | python3 program to find if its possible to distribute balls without repitiion ; function to find if its possible to distribute balls or not ; count array to count how many times each color has occurred ; increasing count of each color every time it appears ; to check if any color appears more than k times if it does we will print no ; 

MAX_CHAR = 26


def distributingBalls(k, n, string):
    a = [0] * MAX_CHAR
    for i in range(n):
        a[ord(string[i]) - ord('a')] += 1
    for i in range(MAX_CHAR):
        if (a[i] > k):
            return False
    return True


if __name__ == "__main__":
    n, k = 6, 3
    string = "aacaab"
    if (distributingBalls(k, n, string)):
        print("YES")
    else:
        print("NO")

# Expected output:
NO
# find substrings that contain all vowels | returns true if x is vowel . ; function to check whether a character is vowel or not ; outer loop picks starting character and inner loop picks ending character . ; if current character is not vowel , then no more result substr1ings possible starting from str1 [ i ] . ; if vowel , then we insert it in hash ; if all vowels are present in current substr1ing ; 
def isVowel(x):
    if (x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u'):
        return True
    return False


def FindSubstr1ing(str1):
    n = len(str1)
    for i in range(n):
        hash = dict()
        for j in range(i, n):
            if (isVowel(str1[j]) == False):
                break
            hash[str1[j]] = 1
            if (len(hash) == 5):
                print(str1[i:j + 1], end=" ")


str1 = "aeoibsddaeiouudb"
FindSubstr1ing(str1)

# Expected output:
aeiou aeiouu
# find if an array contains a string with one mismatch | python 3 program to find if given string is present with one mismatch . ; if the array is empty ; if sizes are same ; if first mismatch ; second mismatch ; 
def check(list, s):
    n = len(list)
    if (n == 0):
        return False
    for i in range(0, n, 1):
        if (len(list[i]) != len(s)):
            continue
        diff = False
        for j in range(0, len(list[i]), 1):
            if (list[i][j] != s[j]):
                if (diff == False):
                    diff = True
                else:
                    diff = False
                    break
        if (diff):
            return True
    return False


if __name__ == '__main__':
    s = []
    s .append("bana")
    s .append("apple")
    s .append("banacb")
    s .append("bonanza")
    s .append("banamf")
    print(int(check(s, "banana")))

# Expected output:
0
# sentence palindrome ( palindrome after removing spaces , dots , . . etc ) | to check sentence is palindrome or not ; lowercase string ; compares character until they are equal ; if there is another symbol in left of sentence ; if there is another symbol in right of sentence ; if characters are equal ; if characters are not equal then sentence is not palindrome ; returns true if sentence is palindrome ; 
def sentencePalindrome(s):
    l, h = 0, len(s) - 1
    s = s .lower()
    while (l <= h):
        if (not (s[l] >= 'a' and s[l] <= 'z')):
            l += 1
        elif (not (s[h] >= 'a' and s[h] <= 'z')):
            h -= 1
        elif (s[l] == s[h]):
            l += 1
            h -= 1
        else:
            return False
    return True


s = "Too hot to hoot."
if (sentencePalindrome(s)):
    print("Sentence is palindrome.")
else:
    print("Sentence is not palindrome.")

# Expected output:
Sentence is palindrome.
# ways to remove one element from a binary string so that xor becomes zero | return number of ways in which xor become zero by remove 1 element ; counting number of 0 and 1 ; if count of ones is even then return count of zero else count of one ; 
def xorZero(str):
    one_count = 0
    zero_count = 0
    n = len(str)
    for i in range(0, n, 1):
        if (str[i] == '1'):
            one_count += 1
        else:
            zero_count += 1
    if (one_count % 2 == 0):
        return zero_count
    return one_count


if __name__ == '__main__':
    str = "11111"
    print(xorZero(str))

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

MAX_CHAR = 26


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


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

# Expected output:
Yes
# check if a string is isogram or not | function to check isogram ; loop to store count of chars and check if it is greater than 1 ; if count > 1 , return false ; 
def check_isogram(string):
    length = len(string)
    mapHash = [0] * 26
    for i in range(length):
        mapHash[ord(string[i]) - ord('a')] += 1
        if (mapHash[ord(string[i]) - ord('a')] > 1):
            return False
    return True


if __name__ == "__main__":
    string = "geeks"
    string2 = "computer"
    if (check_isogram(string)):
        print("True")
    else:
        print("False")
    if (check_isogram(string2)):
        print("True")
    else:
        print("False")

# Expected output:
False
True
# check if a binary string has a 0 between 1 s or not | set 1 ( general approach ) | function returns 1 when string is valid else returns 0 ; find first occurrence of 1 in s [ ] ; find last occurrence of 1 in s [ ] ; check if there is any 0 in range ; 
def checkString(s):
    Len = len(s)
    first = len(s) + 1
    for i in range(Len):
        if (s[i] == '1'):
            first = i
            break
    last = 0
    for i in range(Len - 1, -1, -1):
        if (s[i] == '1'):
            last = i
            break
    for i in range(first, last + 1):
        if (s[i] == '0'):
            return False
    return True


s = "00011111111100000"
if (checkString(s)):
    print("VALID")
else:
    print("NOT VALID")

# Expected output:
VALID
# program to print all substrings of a given string | * function to print all ( n * ( n + 1 ) ) / 2 * substrings of a given string s of length n . ; fix start index in outer loop . reveal new character in inner loop till end of string . prtill - now - formed string . ; 
def printAllSubstrings(s, n):
    for i in range(n):
        temp = ""
        for j in range(i, n):
            temp += s[j]
            print(temp)


s = "Geeky"
printAllSubstrings(s, len(s))

# Expected output:
G
Ge
Gee
Geek
Geeky
e
ee
eek
eeky
e
ek
eky
k
ky
y
# reverse a string preserving space positions | python3 program to implement the above approach ; initialize two pointers as two corners ; move both pointers toward each other ; if character at start or end is space , ignore it ; if both are not spaces , do swap ; 
def preserveSpace(Str):
    n = len(Str)
    Str = list(Str)
    start = 0
    end = n - 1
    while (start < end):
        if (Str[start] == ' '):
            start += 1
            continue
        elif (Str[end] == ' '):
            end -= 1
            continue
        else:
            Str[start], Str[end] = (Str[end], Str[start])
            start += 1
            end -= 1
    print(''.join(Str))


Str = "internship at geeks for geeks"
preserveSpace(Str)

# Expected output:
skeegrofsk ee gtapi hsn retni
# put spaces between words starting with capital letters | function to amend the sentence ; traverse the string ; convert to lowercase if its an uppercase character ; print space before it if its an uppercase character ; print the character ; if lowercase character then just print ; 
def amendSentence(string):
    string = list(string)
    for i in range(len(string)):
        if string[i] >= 'A' and string[i] <= 'Z':
            string[i] = chr(ord(string[i]) + 32)
            if i != 0:
                print(" ", end="")
            print(string[i], end="")
        else:
            print(string[i], end="")


if __name__ == "__main__":
    string = "BruceWayneIsBatman"
    amendSentence(string)

# Expected output:
bruce wayne is batman
# c ++ program to concatenate a string given number of times | function which return string by concatenating it . ; copying given string to temporary string . ; concatenating strings ; 
def repeat(s, n):
    s1 = s
    for i in range(1, n):
        s += s1
    return s


s = "geeks"
n = 3
print(repeat(s, n))

# Expected output:
geeksgeeksgeeks