giulio98/xlcost-single-prompt huggingface dataset:
# count of non | function to return the count of required non - overlapping sub - strings ; to store the required count ; if "010" matches the sub - string starting at current index i ; if "101" matches the sub - string starting at current index i ; 
def countSubStr(s, n):
    count = 0
    i = 0
    while i < (n - 2):
        if (s[i] == '0' and s[i + 1] == '1' and s[i + 2] == '0'):
            count += 1
            i += 3
        elif (s[i] == '1' and s[i + 1] == '0' and s[i + 2] == '1'):
            count += 1
            i += 3
        else:
            i += 1
    return count


if __name__ == "__main__":
    s = "10101010101"
    n = len(s)
    print(countSubStr(s, n))

# Expected output:
3
# find distinct characters in distinct substrings of a string | function to return the count of distinct characters in all the distinct sub - strings of the given string ; to store all the sub - strings ; to store the current sub - string ; to store the characters of the current sub - string ; if current sub - string hasn 't  been stored before ; insert it into the set ; update the count of distinct characters ; 
def countTotalDistinct(string):
    cnt = 0
    items = set()
    for i in range(len(string)):
        temp = ""
        ans = set()
        for j in range(i, len(string)):
            temp = temp + string[j]
            ans .add(string[j])
            if temp not in items:
                items .add(temp)
                cnt += len(ans)
    return cnt


if __name__ == "__main__":
    string = "ABCA"
    print(countTotalDistinct(string))

# Expected output:
18
# partition the string in two parts such that both parts have at least k different characters | function to find the partition of the string such that both parts have at least k different characters ; length of the string ; to check if the current character is already found ; count number of different characters in the left part ; if current character is not already found , increase cnt by 1 ; if count becomes equal to k , we 've  got the first part, therefore,  store current index and break the loop ; increment i by 1 ; clear the map ; assign cnt as 0 ; if the current character is not already found , increase cnt by 1 ; if cnt becomes equal to k , the second part also have k different characters so break it ; if the second part has less than k different characters , then print " not ▁ possible " ; otherwise print both parts ; 
def division_of_string(string, k):
    n = len(string)
    has = {}
    cnt = 0
    i = 0
    while (i < n):
        if string[i]not in has:
            cnt += 1
            has[string[i]] = True
        if (cnt == k):
            ans = i
            break
        i += 1
    i += 1
    has .clear()
    cnt = 0
    while (i < n):
        if (string[i]not in has):
            cnt += 1
            has[string[i]] = True
        if (cnt == k):
            break
        i += 1
    if (cnt < k):
        print("Not possible", end="")
    else:
        i = 0
        while (i <= ans):
            print(string[i], end="")
            i += 1
        print()
        while (i < n):
            print(string[i], end="")
            i += 1
        print()


if __name__ == "__main__":
    string = "geeksforgeeks"
    k = 4
    division_of_string(string, k)

# Expected output:
geeks
forgeeks
# count substrings that contain all vowels | set 2 | function that returns true if c is a vowel ; function to return the count of sub - strings that contain every vowel at least once and no consonant ; map is used to store count of each vowel ; start index is set to 0 initially ; if substring till now have all vowels atleast once increment start index until there are all vowels present between ( start , i ) and add n - i each time ; function to extract all maximum length sub - strings in s that contain only vowels and then calls the countsubstringsutil ( ) to find the count of valid sub - strings in that string ; if current character is a vowel then append it to the temp string ; the sub - string containing all vowels ends here ; if there was a valid sub - string ; reset temp string ; for the last valid sub - string ; 
def isVowel(c):
    return (c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u')


def countSubstringsUtil(s):
    count = 0
    mp = dict .fromkeys(s, 0)
    n = len(s)
    start = 0
    for i in range(n):
        mp[s[i]] += 1
        while (mp['a'] > 0 and mp['e'] > 0 and mp['i']
               > 0 and mp['o'] > 0 and mp['u'] > 0):
            count += n - i
            mp[s[start]] -= 1
            start += 1
    return count


def countSubstrings(s):
    count = 0
    temp = ""
    for i in range(len(s)):
        if (isVowel(s[i])):
            temp += s[i]
        else:
            if (len(temp) > 0):
                count += countSubstringsUtil(temp)
            temp = ""
    if (len(temp) > 0):
        count += countSubstringsUtil(temp)
    return count


if __name__ == "__main__":
    s = "aeouisddaaeeiouua"
    print(countSubstrings(s))

# Expected output:
9
# remove first adjacent pairs of similar characters until possible | function to remove adjacent duplicates ; iterate for every character in the string ; if ans string is empty or its last character does not match with the current character then append this character to the string ; matches with the previous one ; return the answer ; 
def removeDuplicates(S):
    ans = ""
    for it in S:
        if (ans == "" or ans[-1] != it):
            ans += it
        elif (ans[-1] == it):
            ans = ans[:-1]
    return ans


if __name__ == "__main__":
    string = "keexxllx"
    print(removeDuplicates(string))

# Expected output:
kx
# reverse individual words with o ( 1 ) extra space | function to resturn the after reversing the individual words ; pointer to the first character of the first word ; if the current word has ended ; pointer to the last character of the current word ; reverse the current word ; pointer to the first character of the next word ; 
def reverseWords(Str):
    start = 0
    for i in range(len(Str)):
        if (Str[i] == ' ' or i == len(Str) - 1):
            end = i - 1
            if (i == len(Str) - 1):
                end = i
            while (start < end):
                Str[start], Str[end] = Str[end], Str[start]
                start += 1
                end -= 1
            start = i + 1
    return "".join(Str)


Str = "Geeks for Geeks"
Str = [i for i in Str]
print(reverseWords(Str))

# Expected output:
skeeG rof skeeG
# reverse the words of a string using stack | function to reverse the words of the given sentence ; create an empty character array stack ; push words into the stack ; get the words in reverse order ; 
def reverse(k):
    s = []
    token = k .split()
    for word in token:
        s .append(word)
    while (len(s)):
        print(s .pop(), end=" ")


if __name__ == "__main__":
    k = "geeks for geeks"
    reverse(k)

# Expected output:
geeks for geeks
# count of substrings which contains a given character k times | function to count the number of substrings which contains the character c exactly k times ; left and right counters for characters on both sides of subwindow ; left and right pointer on both sides of subwindow ; initialize the frequency ; result and length of string ; initialize the left pointer ; initialize the right pointer ; traverse all the window substrings ; counting the characters on leftside of subwindow ; counting the characters on rightside of subwindow ; add the possible substrings on both sides to result ; setting the frequency for next subwindow ; reset the left , right counters ; 
def countSubString(s, c, k):
    leftCount = 0
    rightCount = 0
    left = 0
    right = 0
    freq = 0
    result = 0
    Len = len(s)
    while (s[left] != c and left < Len):
        left += 1
        leftCount += 1
    right = left + 1
    while (freq != (k - 1) and (right - 1) < Len):
        if (s[right] == c):
            freq += 1
        right += 1
    while (left < Len and (right - 1) < Len):
        while (s[left] != c and left < Len):
            left += 1
            leftCount += 1
        while (right < Len and s[right] != c):
            if (s[right] == c):
                freq += 1
            right += 1
            rightCount += 1
        result = (result + (leftCount + 1) * (rightCount + 1))
        freq = k - 1
        leftCount = 0
        rightCount = 0
        left += 1
        right += 1
    return result


s = "3123231"
c = '3'
k = 2
print(countSubString(s, c, k))

# Expected output:
8
# count of sub | python3 implementation of the approach ; function to return the total required sub - sequences ; find ways for all values of x ; x + 1 ; removing all unnecessary digits ; prefix sum array for x + 1 digit ; sum of squares ; previous sum of all possible pairs ; to find sum of multiplication of all possible pairs ; to prevent overcounting ; adding ways for all possible x ; 

MOD = 1000000007


def solve(test):
    size = len(test)
    total = 0
    for i in range(9):
        x = i
        y = i + 1
        newtest = ""
        for j in range(size):
            if (ord(test[j]) == x + 48 or ord(test[j]) == y + 48):
                newtest += test[j]
        if (len(newtest) > 0):
            size1 = len(newtest)
            prefix = [0 for i in range(size1)]
            for j in range(size1):
                if (ord(newtest[j]) == y + 48):
                    prefix[j] += 1
            for j in range(1, size1):
                prefix[j] += prefix[j - 1]
            count = 0
            firstcount = 0
            ss = 0
            prev = 0
            for j in range(size1):
                if (ord(newtest[j]) == x + 48):
                    count += 1
                    firstcount += 1
                else:
                    ss += count * count
                    pairsum = (firstcount * firstcount - ss) // 2
                    temp = pairsum
                    pairsum -= prev
                    prev = temp
                    secondway = prefix[size1 - 1]
                    if (j != 0):
                        secondway -= prefix[j - 1]
                    answer = count * (count - 1) * secondway * (secondway - 1)
                    answer //= 4
                    answer += (pairsum * secondway * (secondway - 1)) // 2
                    total += answer
                    count = 0
    return total


test = "13134422"
print(solve(test))

# Expected output:
2
# find if it is possible to make a binary string which contanins given number of "0" , "1" , "01" and "10" as sub sequences | function that returns true if it is possible to make a binary string consisting of l 0 ' s , ▁ m ▁ 1' s , x "01" sub - sequences and y "10" sub - sequences ; 
def isPossible(l, m, x, y):
    if (l * m == x + y):
        return True
    return False


if __name__ == "__main__":
    l = 3
    m = 2
    x = 4
    y = 2
    if (isPossible(l, m, x, y)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# count pairs of characters in a string whose ascii value difference is k | python3 implementation of the approach ; function to return the count of required pairs of characters ; length of the string ; to store the frequency of each character ; update the frequency of each character ; to store the required count of pairs ; if ascii value difference is zero ; if there exists similar characters more than once ; if there exits characters with ascii value difference as k ; return the required count ; 

MAX = 26


def countPairs(string, k):
    n = len(string)
    freq = [0] * MAX
    for i in range(n):
        freq[ord(string[i]) - ord('a')] += 1
    cnt = 0
    if (k == 0):
        for i in range(MAX):
            if (freq[i] > 1):
                cnt += ((freq[i] * (freq[i] - 1)) // 2)
    else:
        for i in range(MAX):
            if (freq[i] > 0 and i + k < MAX and freq[i + k] > 0):
                cnt += (freq[i] * freq[i + k])
    return cnt


if __name__ == "__main__":
    string = "abcdab"
    k = 0
    print(countPairs(string, k))

# Expected output:
2
# count of three non | function that returns true if s [ i ... j ] + s [ k ... l ] + s [ p ... q ] is a palindrome ; function to return the count of valid sub - strings ; to store the count of required sub - strings ; for choosing the first sub - string ; for choosing the second sub - string ; for choosing the third sub - string ; check if the concatenation is a palindrome ; 
def isPalin(i, j, k, l, p, q, s):
    start = i
    end = q
    while (start < end):
        if (s[start] != s[end]):
            return False
        start += 1
        if (start == j + 1):
            start = k
        end -= 1
        if (end == p - 1):
            end = l
    return True


def countSubStr(s):
    count = 0
    n = len(s)
    for i in range(n - 2):
        for j in range(i, n - 2):
            for k in range(j + 1, n - 1):
                for l in range(k, n - 1):
                    for p in range(l + 1, n):
                        for q in range(p, n):
                            if (isPalin(i, j, k, l, p, q, s)):
                                count += 1
    return count


if __name__ == "__main__":
    s = "abca"
    print(countSubStr(s))

# Expected output:
2
# find the sum of the ascii values of characters which are present at prime positions | python3 implementation of the approach ; function that returns true if n is prime ; function to return the sum of the ascii values of the characters which are present at prime positions ; to store the sum ; for every character ; if current position is prime then add the ascii value of the character at the current position ; 

from math import sqrt


def isPrime(n):
    if (n == 0 or n == 1):
        return False
    for i in range(2, int(sqrt(n)) + 1):
        if (n % i == 0):
            return False
    return True


def sumAscii(string, n):
    sum = 0
    for i in range(n):
        if (isPrime(i + 1)):
            sum += ord(string[i])
    return sum


if __name__ == "__main__":
    string = "geeksforgeeks"
    n = len(string)
    print(sumAscii(string, n))

# Expected output:
644
# count the nodes of a tree whose weighted string does not contain any duplicate characters | python3 implementation of the approach ; function that returns true if the string contains unique characters ; function to perform dfs ; if weight of the current node node contains unique characters ; 

cnt = 0
graph = [[]for i in range(100)]
weight = [0] * 100


def uniqueChars(x):
    mp = {}
    n = len(x)
    for i in range(n):
        if x[i]not in mp:
            mp[x[i]] = 0
        mp[x[i]] += 1
    if (len(mp) == len(x)):
        return True
    else:
        return False


def dfs(node, parent):
    global cnt, x
    if (uniqueChars(weight[node])):
        cnt += 1
    for to in graph[node]:
        if (to == parent):
            continue
        dfs(to, node)


x = 5
weight[1] = "abc"
weight[2] = "aba"
weight[3] = "bcb"
weight[4] = "moh"
weight[5] = "aa"
graph[1].append(2)
graph[2].append(3)
graph[2].append(4)
graph[1].append(5)
dfs(1, 1)
print(cnt)

# Expected output:
2
# check if a string contains two non overlapping sub | function that returns true if s contains two non overlapping sub strings " geek " and " keeg " ; if " geek " and " keeg " are both present in s without over - lapping and " keeg " starts after " geek " ends ; 
def isValid(s):
    p = ""
    p = s .find("geek")
    if (s .find("keeg", p + 4)):
        return True
    return False


if __name__ == "__main__":
    s = "geekeekeeg"
    if (isValid(s)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# find the last non repeating character in string | maximum distinct characters possible ; function to return the last non - repeating character ; to store the frequency of each of the character of the given string ; update the frequencies ; starting from the last character ; current character ; if frequency of the current character is 1 then return the character ; all the characters of the string are repeating ; 

MAX = 256


def lastNonRepeating(string, n):
    freq = [0] * MAX
    for i in range(n):
        freq[ord(string[i])] += 1
    for i in range(n - 1, -1, -1):
        ch = string[i]
        if (freq[ord(ch)] == 1):
            return ("" + ch)
    return "-1"


if __name__ == "__main__":
    string = "GeeksForGeeks"
    n = len(string)
    print(lastNonRepeating(string, n))

# Expected output:
r
# minimum number of operations on a binary string such that it gives 10 ^ a as remainder when divided by 10 ^ b | function to return the minimum number of operations on a binary string such that it gives 10 ^ a as remainder when divided by 10 ^ b ; initialize result ; loop through last b digits ; 
def findCount(s, n, a, b):
    res = 0
    for i in range(b):
        if (i == a):
            res += (s[n - i - 1] != '1')
        else:
            res += (s[n - i - 1] != '0')
    return res


if __name__ == '__main__':
    str = "1001011001"
    N = len(str)
    A = 3
    B = 6
    print(findCount(str, N, A, B))

# Expected output:
2
# find letter 's position in alphabet using bit operation | python3 implementation of the approach ; function to calculate the position of characters ; performing and operation with number 31 ; 

NUM = 31


def positions(str):
    for i in str:
        print((ord(i) & NUM), end=" ")


str = "Geeks"
positions(str)

# Expected output:
7 5 5 11 19
# generate all permutations of a string that follow given constraints | simple python program to print all permutations of a string that follow given constraint ; check if current permutation is valid ; recursively generate all permutation ; 
def permute(str, l, r):
    if (l == r):
        if "AB"not in ''.join(str):
            print(''.join(str), end=" ")
        return
    for i in range(l, r + 1):
        str[l], str[i] = str[i], str[l]
        permute(str, l + 1, r)
        str[l], str[i] = str[i], str[l]


str = "ABC"
permute(list(str), 0, len(str) - 1)

# Expected output:
ACB BAC BCA CBA
# length of the longest substring that do not contain any palindrome | function to find the length of the longest substring ; initializing the variables ; checking palindrome of size 2 example : aa ; checking palindrome of size 3 example : aba ; else : incrementing length of substring ; if there exits single character then it is always palindrome ; 
def lenoflongestnonpalindrome(s):
    max1, length = 1, 0
    for i in range(0, len(s) - 1):
        if s[i] == s[i + 1]:
            length = 0
        elif s[i + 1] == s[i - 1] and i > 0:
            length = 1
            length += 1
    if max1 == 1:
        return 0
    else:
        return max1


if __name__ == "__main__":
    s = "synapse"
    print(lenoflongestnonpalindrome(s))

# Expected output:
0
# calculate score for the given binary string | function to return the score for the given binary string ; traverse through string character ; initialize current chunk 's size ; get current character ; calculate total chunk size of same characters ; add / subtract pow ( chunksize , 2 ) depending upon character ; return the score ; 
def calcScore(str):
    score = 0
    len1 = len(str)
    i = 0
    while (i < len1):
        chunkSize = 1
        currentChar = str[i]
        i += 1
        while (i < len1 and str[i] == currentChar):
            chunkSize += 1
            i += 1
        if (currentChar == '1'):
            score += pow(chunkSize, 2)
        else:
            score -= pow(chunkSize, 2)
    return score


if __name__ == '__main__':
    str = "11011"
    print(calcScore(str))

# Expected output:
7
# number of sub | function to return the count of required sub - strings ; left and right counters for characters on both sides of sub - string window ; left and right pointer on both sides of sub - string window ; initialize the frequency ; result and length of string ; initialize the left pointer ; initialize the right pointer ; traverse all the window sub - strings ; counting the characters on left side of the sub - string window ; counting the characters on right side of the sub - string window ; add the possible sub - strings on both sides to result ; setting the frequency for next sub - string window ; reset the left and right counters ; 
def countSubString(s, c, k):
    leftCount = 0
    rightCount = 0
    left = 0
    right = 0
    freq = 0
    result = 0
    len1 = len(s)
    while (s[left] != c and left < len1):
        left += 1
        leftCount += 1
    right = left + 1
    while (freq != (k - 1) and (right - 1) < len1):
        if (s[right] == c):
            freq += 1
        right += 1
    while (left < len1 and (right - 1) < len1):
        while (s[left] != c and left < len1):
            left += 1
            leftCount += 1
        while (right < len1 and s[right] != c):
            if (s[right] == c):
                freq += 1
            right += 1
            rightCount += 1
        result = (result + (leftCount + 1) * (rightCount + 1))
        freq = k - 1
        leftCount = 0
        rightCount = 0
        left += 1
        right += 1
    return result


if __name__ == '__main__':
    s = "abada"
    c = 'a'
    k = 2
    print(countSubString(s, c, k))

# Expected output:
4
# number of times the given string occurs in the array in the range [ l , r ] | python implementation of the approach ; function to return the number of occurrences of ; to store the indices of strings in the array ; if current string doesn 't  have an entry in the map  then create the entry ; if the given string is not present in the array ; if the given string is present in the array ; 

from bisect import bisect_right as upper_bound
from collections import defaultdict


def numOccurences(arr: list, n: int, string: str, L: int, R: int) -> int:
    M = defaultdict(lambda: list)
    for i in range(n):
        temp = arr[i]
        if temp not in M:
            A = []
            A .append(i + 1)
            M[temp] = A
        else:
            M[temp].append(i + 1)
    if string not in M:
        return 0
    A = M[string]
    y = upper_bound(A, R)
    x = upper_bound(A, L - 1)
    return (y - x)


if __name__ == "__main__":
    arr = ["abc", "abcabc", "abc"]
    n = len(arr)
    L = 1
    R = 3
    string = "abc"
    print(numOccurences(arr, n, string, L, R))

# Expected output:
2
# check whether the given string is a valid identifier | function that returns true if str1 is a valid identifier ; if first character is invalid ; traverse the for the rest of the characters ; is a valid identifier ; 
def isValid(str1, n):
    if (((ord(str1[0]) >= ord('a') and ord(str1[0]) <= ord('z')) or (ord(str1[0]) >= ord(
            'A') and ord(str1[0]) <= ord('Z')) or ord(str1[0]) == ord('_')) == False):
        return False
    for i in range(1, len(str1)):
        if (((ord(str1[i]) >= ord('a') and ord(str1[i]) <= ord('z')) or (ord(str1[i]) >= ord('A') and ord(str1[i]) <= ord(
                'Z')) or (ord(str1[i]) >= ord('0') and ord(str1[i]) <= ord('9')) or ord(str1[i]) == ord('_')) == False):
            return False
    return True


str1 = "_geeks123"
n = len(str1)
if (isValid(str1, n)):
    print("Valid")
else:
    print("Invalid")

# Expected output:
Valid
# check if all the 1 's in a binary string are equidistant or not | function that returns true if all the 1 's in the binary s are equidistant ; initialize vector to store the position of 1 's ; store the positions of 1 's ; size of the position vector ; if condition isn 't satisfied ; 
def check(s, l):
    pos = []
    for i in range(l):
        if (s[i] == '1'):
            pos .append(i)
    t = len(pos)
    for i in range(1, t):
        if ((pos[i] - pos[i - 1]) != (pos[1] - pos[0])):
            return False
    return True


s = "100010001000"
l = len(s)
if (check(s, l)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes