giulio98/xlcost-single-prompt huggingface dataset:
# count of lexicographically smaller characters on right | function to count the smaller characters on the right of index i ; store the length of string ; initialize each elements of arr to zero ; array to store count of smaller characters on the right side of that index ; initialize the variable to store the count of characters smaller than that at index i ; adding the count of characters smaller than index i ; print the count of characters smaller than index i stored in ans array ; 
def countSmaller(str):
    n = len(str)
    arr = [0] * 26
    ans = [0] * n
    for i in range(n - 1, -1, -1):
        arr[ord(str[i]) - ord('a')] += 1
        ct = 0
        for j in range(ord(str[i]) - ord('a')):
            ct += arr[j]
        ans[i] = ct
    for i in range(n):
        print(ans[i], end=" ")


if __name__ == '__main__':
    str = "edcbaa"
    countSmaller(str)

# Expected output:
5 4 3 2 0 0
# count of words ending at the given suffix in java | function declared to return the count of words in the given sentence that end with the given suffix ; variable to store count ; split function used to extract words from sentence in form of list ; using for loop with ' in ' to extract elements of list ; returning the count ; 
def endingWith(str, suff):
    c = 0
    wrd = str .split(" ")
    for l in wrd:
        if l .endswith(suff):
            c += 1
    return c


str = "GeeksForGeeks is a computer science portal for geeks"
suff = "ks"
print(endingWith(str, suff))

# Expected output:
2
# character whose frequency is equal to the sum of frequencies of other characters of the given string | function that returns true if some character exists in the given string whose frequency is equal to the sum frequencies of other characters of the string ; if string is of odd length ; to store the frequency of each character of the string ; update the frequencies of the characters ; no such character exists ; 
def isFrequencyEqual(string, length):
    if length % 2 == 1:
        return False
    freq = [0] * 26
    for i in range(0, length):
        freq[ord(string[i]) - ord('a')] += 1
    for i in range(0, 26):
        if freq[i] == length // 2:
            return True
    return False


if __name__ == "__main__":
    string = "geeksforgeeks"
    length = len(string)
    if isFrequencyEqual(string, length):
        print("Yes")
    else:
        print("No")

# Expected output:
No
# minimum replacements to make adjacent characters unequal in a ternary string | function to count the number of minimal replacements ; find the length of the string ; iterate in the string ; check if adjacent is similar ; if not the last pair ; check for character which is not same in i + 1 and i - 1 ; last pair ; check for character which is not same in i - 1 index ; 
def countMinimalReplacements(s):
    n = len(s)
    cnt = 0
    for i in range(1, n):
        if (s[i] == s[i - 1]):
            cnt += 1
            if (i != (n - 1)):
                s = list(s)
                for j in "012":
                    if (j != s[i + 1] and j != s[i - 1]):
                        s[i] = j
                        break
                s = ''.join(s)
            else:
                s = list(s)
                for k in "012":
                    if (k != s[i - 1]):
                        s[i] = k
                        break
                s = ''.join(s)
    return cnt


if __name__ == '__main__':
    s = "201220211"
    print(countMinimalReplacements(s))

# Expected output:
2
# check whether the frequencies of all the characters in a string are prime or not | python3 implementation of above approach ; function that returns true if n is prime else false ; 1 is not prime ; check if there is any factor or not ; function that returns true if the frequencies of all the characters of s are prime ; create a map to store the frequencies of characters ; update the frequency ; check whether all the frequencies are prime or not ; 

import math as mt


def isPrime(n):
    i = 2
    if (n == 1):
        return False
    for i in range(2, mt .ceil(mt .sqrt(n))):
        if (n % i == 0):
            return False
    return True


def check_frequency(s):
    m = dict()
    for i in range(len(s)):
        if s[i] in m .keys():
            m[s[i]] += 1
        else:
            m[s[i]] = 1
    for ch in m:
        if m[ch] > 0 and isPrime(m[ch]) == False:
            return False
    return True


s = "geeksforgeeks"
if (check_frequency(s)):
    print("Yes")
else:
    print("No")

# Expected output:
No
# find the count of substrings in alphabetic order | function to find number of substrings ; iterate over string length ; if any two chars are in alphabetic order ; find next char not in order ; return the result ; 
def findSubstringCount(str):
    result = 0
    n = len(str)
    for i in range(n - 1):
        if (ord(str[i]) + 1 == ord(str[i + 1])):
            result += 1
            while (ord(str[i]) + 1 == ord(str[i + 1])):
                i += 1
    return result


if __name__ == "__main__":
    str = "alphabet"
    print(findSubstringCount(str))

# Expected output:
1
# first non | '' python3 implementation to find non repeating character using 1d array and one traversal ; the function returns index of the first non - repeating character in a string . if all characters are repeating then returns int_max ; initialize all character as absent ; after below loop , the value of arr [ x ] is going to be index of of x if x appears only once . else the value is going to be either - 1 or - 2. ; if this character occurs only once and appears before the current result , then update the result ; 

import math as mt
NO_OF_CHARS = 256


def firstNonRepeating(string):
    arr = [-1 for i in range(NO_OF_CHARS)]
    for i in range(len(string)):
        if arr[ord(string[i])] == -1:
            arr[ord(string[i])] = i
        else:
            arr[ord(string[i])] = -2
    res = 10 ** 18
    for i in range(NO_OF_CHARS):
        if arr[i] >= 0:
            res = min(res, arr[i])
    return res


string = "geeksforgeeks"
index = firstNonRepeating(string)
if index == 10 ** 18:
    print("Either all characters are repeating or string is empty")
else:
    print("First non-repeating character is", string[index])

# Expected output:
First non-repeating character is f
# character replacement after removing duplicates from a string | function to minimize string ; duplicate characters are removed ; checks if character has previously occurred or not if not then add it to the minimized string 'mstr ; utility function to print the minimized , replaced string ; creating final string by replacing character ; index calculation ; 
def minimize(string):

    mstr = " "
    flagchar = [0] * 26
    l = len(string)
    for i in range(0, len(string)):

        ch = string[i]
        if flagchar[ord(ch)-97] == 0:

            mstr = mstr + ch
            flagchar[ord(ch)-97] = 1

    return mstr


def replaceMinimizeUtil(string):

    finalStr = ""
    l = len(string)
    minimizedStr = minimize(string)
    for i in range(0, len(minimizedStr)):

        ch = ord(minimizedStr[i])
        index = (ch * ch) % l
        finalStr = finalStr + string[index]

    print("Final string:", finalStr)


if __name__ == "__main__":
    string = "geeks"
    replaceMinimizeUtil(string)

# Expected output:
Final string: ssesg
# latin alphabet cipher | function for calculating the encryption ; 
def cipher(str):
    for i in range(len(str)):
        if str[i].isalpha() == 0 and str[i] != " ":
            print("Enter only alphabets and space")
            return
    print("Encrypted Code using Latin Alphabet")
    for i in range(len(str)):
        if str[i] >= "A" and str[i] <= "Z":
            print(ord(str[i]) - ord("A") + 1, end=" ")
        elif str[i] >= "a" and str[i] <= 'z':
            print(ord(str[i]) - ord("a") + 1, end=" ")
        if str[i] == " ":
            print(str[i])
    print()


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

# Expected output:
Encrypted Code using Latin Alphabet
7 5 5 11 19 6 15 18 7 5 5 11 19
# count palindrome words in a sentence | function to check if a word is palindrome ; function to count palindrome words ; splitting each word as spaces as delimiter and storing it into a list ; iterating every element from list and checking if it is a palindrome . ; if the word is a palindrome increment the count . ; 
def checkPalin(word):
    if word .lower() == word .lower()[::-1]:
        return True


def countPalin(str):
    count = 0
    listOfWords = str .split(" ")
    for elements in listOfWords:
        if (checkPalin(elements)):
            count += 1
    print(count)


countPalin("Madam Arora teaches malayalam")
countPalin("Nitin speaks malayalam")

# Expected output:
3
2
# remove the forbidden strings | pre [ ] keeps record of the characters of w that need to be changed ; stores the forbidden strings ; function to check if the particula r substring is present in w at position ; if length of substring from this position is greater than length of w then return ; n and n1 are used to check for substring without considering the case of the letters in w by comparing the difference of ascii values ; if same == true then it means a substring was found starting at position therefore all characters from position to length of substring found need to be changed therefore they needs to be marked ; function implementing logic ; to verify if any substring is starting from index i ; modifying the string w according to th rules ; this condition checks if w [ i ] = upper ( letter ) ; this condition checks if w [ i ] is any lowercase letter apart from letter . if true replace it with letter ; this condition checks if w [ i ] is any uppercase letter apart from letter . if true then replace it with upper ( letter ) . ; number of forbidden strings ; 

pre = [False] * 100
s = [None] * 110


def verify(position, index):
    l = len(w)
    k = len(s[index])
    if (position + k > l):
        return
    same = True
    for i in range(position, position + k):
        ch = w[i]
        ch1 = s[index][i - position]
        if (ch >= 'a' and ch <= 'z'):
            n = ord(ch) - ord('a')
        else:
            n = ord(ch) - ord('A')
        if (ch1 >= 'a' and ch1 <= 'z'):
            n1 = ord(ch1) - ord('a')
        else:
            n1 = ord(ch1) - ord('A')
        if (n != n1):
            same = False
    if (same):
        for i in range(position, position + k):
            pre[i] = True
        return


def solve():
    l = len(w)
    p = ord(letter) - ord('a')
    for i in range(l):
        for j in range(n):
            verify(i, j)
    for i in range(l):
        if (pre[i]):
            if (w[i] == letter):
                w[i] = 'b'if (letter == 'a')else 'a'
            elif (w[i] == str(ord('A') + p)):
                w[i] = 'B'if (letter == 'a')else 'A'
            elif (w[i] >= 'a' and w[i] <= 'z'):
                w[i] = letter
            elif (w[i] >= 'A' and w[i] <= 'Z'):
                w[i] = chr(ord('A') + p)
    print(''.join(w))


n = 3
s[0] = "etr"
s[1] = "ed"
s[2] = "ied"
w = "PEtrUnited"
w = list(w)
letter = 'd'
solve()

# Expected output:
PDddUnitda
# round the given number to nearest multiple of 10 | function to round the number ; smaller multiple ; larger multiple ; return of closest of two ; 
def round(n):
    a = (n // 10) * 10
    b = a + 10
    return (b if n - a > b - n else a)


n = 4722
print(round(n))

# Expected output:
4720
# breaking a number such that first part is integral division of second by a power of 10 | python3 program to count ways to divide a string in two parts a and b such that b / pow ( 10 , p ) == a ; substring representing int a ; no of digits in a ; consider only most significant l1 characters of remaining string for int b ; if any of a or b contains leading 0 s discard this ; if both are equal ; 
def calculate(N):
    length = len(N)
    l = int((length) / 2)
    count = 0
    for i in range(l + 1):
        s = N[0:0 + i]
        l1 = len(s)
        t = N[i:l1 + i]
        try:
            if s[0] == '0' or t[0] == '0':
                continue
        except BaseException:
            continue
        if s == t:
            count += 1
    return count


N = str("2202200")
print(calculate(N))

# Expected output:
2
# program to check strength of password | python3 program to check if a given password is strong or not . ; checking lower alphabet in string ; strength of password ; 
def printStrongNess(input_string):
    n = len(input_string)
    hasLower = False
    hasUpper = False
    hasDigit = False
    specialChar = False
    normalChars = "abcdefghijklmnopqrstu"
    for i in range(n):
        if input_string[i].islower():
            hasLower = True
        if input_string[i].isupper():
            hasUpper = True
        if input_string[i].isdigit():
            hasDigit = True
        if input_string[i]not in normalChars:
            specialChar = True
    print("Strength of password:-", end="")
    if (hasLower and hasUpper and hasDigit and specialChar and n >= 8):
        print("Strong")
    elif ((hasLower or hasUpper) and specialChar and n >= 6):
        print("Moderate")
    else:
        print("Weak")


if __name__ == "__main__":
    input_string = "GeeksforGeeks!@12"
    printStrongNess(input_string)

# Expected output:
Strength of password:-Strong
# string with k distinct characters and no same characters adjacent | function to find a string of length n with k distinct characters . ; initialize result with first k latin letters ; fill remaining n - k letters by repeating k letters again and again . ; 
def findString(n, k):
    res = ""
    for i in range(k):
        res = res + chr(ord('a') + i)
    count = 0
    for i in range(n - k):
        res = res + chr(ord('a') + count)
        count += 1
        if (count == k):
            count = 0
    return res


if __name__ == "__main__":
    n = 5
    k = 2
    print(findString(n, k))

# Expected output:
ababa
# find substrings that contain all vowels | returns true if x is vowel . ; function to check whether a character is vowel or not ; function to findsubstrings of string ; hash = set ( ) ; to store vowels ; if current character is vowel then insert into hash ; if all vowels are present in current substring ; 
def isVowel(x):
    return (x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u')


def FindSubstring(str):
    start = 0
    hash = set()
    for i in range(len(str)):
        if (isVowel(str[i])):
            hash .add(str[i])
            if (len(hash) == 5):
                print(str[start:i + 1], end=" ")
        else:
            start = i + 1
            hash .clear()


str = "aeoibsddaeiouudb"
FindSubstring(str)

# Expected output:
aeiou aeiouu
# concatenated string with uncommon characters of two strings | python3 program find concatenated string with uncommon characters of given strings ; res = " " result ; store all characters of s2 in map ; find characters of s1 that are not present in s2 and append to result ; find characters of s2 that are not present in s1 . ; 
def concatenetedString(s1, s2):
    res = ''
    m = {}
    for i in range(0, len(s2)):
        m[s2[i]] = 1
    for i in range(0, len(s1)):
        if (not s1[i] in m):
            res = res + s1[i]
        else:
            m[s1[i]] = 2
    for i in range(0, len(s2)):
        if (m[s2[i]] == 1):
            res = res + s2[i]
    return res


if __name__ == "__main__":
    s1 = "abcs"
    s2 = "cxzca"
    print(concatenetedString(s1, s2))

# Expected output:
bsxz
# null cipher | function to decode the message . ; store the decoded string ; found variable is used to tell that the encoded encoded character is found in that particular word . ; set found variable to false whenever we find whitespace , meaning that encoded character for new word is not found ; 
def decode(string):
    res = ""
    found = False
    for character in string:
        if character == ' ':
            found = False
            continue
        if not found:
            if character >= 'A' and character <= 'Z' or character >= 'a' and character <= 'z':
                res += character
                found = True
    return res .lower()


if __name__ == "__main__":
    input = "A Step by Step Guide for Placement Preparation by GeeksforGeeks"
    print("Enciphered Message:", decode(input))

# Expected output:
Enciphered Message: asbsgfppbg
# program to count vowels in a string ( iterative and recursive ) | function to check the vowel ; to count total number of vowel from 0 to n ; 
def isVowel(ch):
    return ch .upper() in ['A', 'E', 'I', 'O', 'U']


def countVovels(str, n):
    if (n == 1):
        return isVowel(str[n - 1])
    return (countVovels(str, n - 1) + isVowel(str[n - 1]))


str = "abc de"
print(countVovels(str, len(str)))

# Expected output:
2
# generate all rotations of a given string | print all the rotated string . ; concatenate str with itself ; print all substrings of size n . note that size of temp is 2 n ; 
def printRotatedString(string):
    n = len(string)
    temp = string + string
    for i in range(n):
        for j in range(n):
            print(temp[i + j], end="")
        print()


if __name__ == "__main__":
    string = "geeks"
    printRotatedString(string)

# Expected output:
geeks
eeksg
eksge
ksgee
sgeek
# check if frequency of all characters can become same by one removal | python3 program to get same frequency character string by removal of at most one char ; utility method to get index of character ch in lower alphabet characters ; returns true if all non - zero elements values are same ; get first non - zero element ; check equality of each element with variable same ; returns true if we can make all character frequencies same ; fill frequency array ; if all frequencies are same , then return true ; try decreasing frequency of all character by one and then check all equality of all non - zero frequencies ; check character only if it occurs in str ; 

M = 26


def getIdx(ch):
    return (ord(ch) - ord('a'))


def allSame(freq, N):
    for i in range(0, N):
        if (freq[i] > 0):
            same = freq[i]
            break
    for j in range(i + 1, N):
        if (freq[j] > 0 and freq[j] != same):
            return False
    return True


def possibleSameCharFreqByOneRemoval(str1):
    l = len(str1)
    freq = [0] * M
    for i in range(0, l):
        freq[getIdx(str1[i])] += 1
    if (allSame(freq, M)):
        return True
    for i in range(0, 26):
        if (freq[i] > 0):
            freq[i] -= 1
            if (allSame(freq, M)):
                return True
            freq[i] += 1
    return False


if __name__ == "__main__":
    str1 = "xyyzz"
    if (possibleSameCharFreqByOneRemoval(str1)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# check if a large number is divisible by 11 or not | function to find that number divisible by 11 or not ; compute sum of even and odd digit sums ; when i is even , position of digit is odd ; check its difference is divisible by 11 or not ; 
def check(st):
    n = len(st)
    oddDigSum = 0
    evenDigSum = 0
    for i in range(0, n):
        if (i % 2 == 0):
            oddDigSum = oddDigSum + ((int)(st[i]))
        else:
            evenDigSum = evenDigSum + ((int)(st[i]))
    return ((oddDigSum - evenDigSum) % 11 == 0)


st = "76945"
if (check(st)):
    print("Yes")
else:
    print("No ")

# Expected output:
Yes
# hamming distance between two strings | function to calculate hamming distance ; 
def hammingDist(str1, str2):
    i = 0
    count = 0
    while (i < len(str1)):
        if (str1[i] != str2[i]):
            count += 1
        i += 1
    return count


str1 = "geekspractice"
str2 = "nerdspractise"
print(hammingDist(str1, str2))

# Expected output:
4
# check if two strings are k | python3 program to check if two strings are k anagram or not . ; function to check that is k - anagram or not ; if both strings are not of equal length then return false ; store the occurrence of all characters in a hash_array ; count number of characters that are different in both strings ; return true if count is less than or equal to k ; 

MAX_CHAR = 26


def arekAnagrams(str1, str2, k):
    n = len(str1)
    if (len(str2) != n):
        return False
    count1 = [0] * MAX_CHAR
    count2 = [0] * MAX_CHAR
    for i in range(n):
        count1[ord(str1[i]) - ord('a')] += 1
    for i in range(n):
        count2[ord(str2[i]) - ord('a')] += 1
    count = 0
    for i in range(MAX_CHAR):
        if (count1[i] > count2[i]):
            count = count + abs(count1[i] - count2[i])
    return (count <= k)


if __name__ == '__main__':
    str1 = "anagram"
    str2 = "grammar"
    k = 2
    if (arekAnagrams(str1, str2, k)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# remove spaces from a given string | function to remove all spaces from a given string ; to keep track of non - space character count ; traverse the given string . if current character is not space , then place it at index 'count++ ; utility function ; 
def toString(List):
    return ''.join(List)


def removeSpaces(string):
    count = 0
    list = []

    for i in range(len(string)):
        if string[i] != ' ':
            list .append(string[i])
    return toString(list)


string = "g eeks for ge eeks "
print(removeSpaces(string))

# Expected output:
geeksforgeeeks
# given a binary string , count number of substrings that start and end with 1. | a python3 program to count number of substrings starting and ending with 1 ; count of 1 's in input string ; traverse input string and count of 1 's in it ; return count of possible pairs among m 1 's ; 
def countSubStr(st, n):
    m = 0
    for i in range(0, n):
        if (st[i] == '1'):
            m = m + 1
    return m * (m - 1) // 2


st = "00100101"
list(st)
n = len(st)
print(countSubStr(st, n), end="")

# Expected output:
3
# given a number as a string , find the number of contiguous subsequences which recursively add up to 9 | python 3 program to count substrings with recursive sum equal to 9 ; count = 0 to store result ; consider every character as beginning of substring ; sum of digits in current substring ; one by one choose every character as an ending character ; add current digit to sum , if sum becomes multiple of 5 then increment count . let us do modular arithmetic to avoid overflow for big strings ; 
def count9s(number):
    count = 0
    n = len(number)
    for i in range(n):
        sum = ord(number[i]) - ord('0')
        if (number[i] == '9'):
            count += 1
        for j in range(i + 1, n):
            sum = (sum + ord(number[j]) - ord('0')) % 9
            if (sum == 0):
                count += 1
    return count


if __name__ == "__main__":
    print(count9s("4189"))
    print(count9s("1809"))

# Expected output:
3
5
# generate n | python3 program to generate n - bit gray codes ; this function generates all n bit gray codes and prints the generated codes ; base case ; ' arr ' will store all generated codes ; start with one - bit pattern ; every iteration of this loop generates 2 * i codes from previously generated i codes . ; enter the prviously generated codes again in arr [ ] in reverse order . nor arr [ ] has double number of codes . ; append 0 to the first half ; append 1 to the second half ; prcontents of arr [ ] ; 

import math as mt


def generateGrayarr(n):
    if (n <= 0):
        return
    arr = list()
    arr .append("0")
    arr .append("1")
    i = 2
    j = 0
    while (True):
        if i >= 1 << n:
            break
        for j in range(i - 1, -1, -1):
            arr .append(arr[j])
        for j in range(i):
            arr[j] = "0" + arr[j]
        for j in range(i, 2 * i):
            arr[j] = "1" + arr[j]
        i = i << 1
    for i in range(len(arr)):
        print(arr[i])


generateGrayarr(3)

# Expected output:
000
001
011
010
110
111
101
100