giulio98/xlcost-single-prompt huggingface dataset:
# binary search a string | returns index of x if it is present in arr [ ] , else return - 1 ; check if x is present at mid ; if x greater , ignore left half ; if x is smaller , ignore right half ; 
def binarySearch(arr, x):
    l = 0
    r = len(arr)
    while (l <= r):
        m = l + ((r - l) // 2)
        res = (x == arr[m])
        if (res == 0):
            return m - 1
        if (res > 0):
            l = m + 1
        else:
            r = m - 1
    return -1


if __name__ == "__main__":
    arr = ["contribute", "geeks", "ide", "practice"]
    x = "ide"
    result = binarySearch(arr, x)
    if (result == -1):
        print("Element not present")
    else:
        print("Element found at index", result)

# Expected output:
Element found at index 2
# count characters in a string whose ascii values are prime | python3 implementation of above approach ; function to find prime characters in the string ; use sieve to find all prime numbers less than or equal to max_val create a boolean array " prime [ 0 . . n ] " . a value in prime [ i ] will finally be false if i is not a prime , else true . ; 0 and 1 are not primes ; if prime [ p ] is not changed , then it is a prime ; update all multiples of p ; traverse all the characters ; 

from math import sqrt
max_val = 257


def PrimeCharacters(s):
    prime = [True] * (max_val + 1)
    prime[0] = False
    prime[1] = False
    for p in range(2, int(sqrt(max_val)) + 1):
        if (prime[p]):
            for i in range(2 * p, max_val + 1, p):
                prime[i] = False
    count = 0
    for i in range(len(s)):
        if (prime[ord(s[i])]):
            count += 1
    return count


if __name__ == "__main__":
    S = "geeksforgeeks"
    print(PrimeCharacters(S))

# Expected output:
8
# students with maximum average score of three subjects | function to find the list of students having maximum average score ; variables to store maximum average score ; list to store names of students having maximum average score ; traversing the file data ; finding average score of a student ; clear the list and add name of student having current maximum average score in the list ; printing the maximum average score and names of students having this maximum average score as per the order in the file . ; 
def getStudentsList(file):
    maxAvgScore = 0
    names = []
    for i in range(0, len(file), 4):
        avgScore = (int(file[i + 1]) +
                    int(file[i + 2]) + int(file[i + 3])) // 3
        if avgScore > maxAvgScore:
            maxAvgScore = avgScore
            names .clear()
            names .append(file[i])
        elif avgScore == maxAvgScore:
            names .add(file[i])
    for i in range(len(names)):
        print(names[i], end=" ")
    print(maxAvgScore)


if __name__ == "__main__":
    file = ["Shrikanth", "20", "30", "10", "Ram", "100", "50", "10"]
    getStudentsList(file)

# Expected output:
Ram 53
# number of sub | python3 program to find the number of sub - strings of s1 which are anagram of any sub - string of s2 ; this function returns true if contents of arr1 [ ] and arr2 [ ] are same , otherwise false . ; this function search for all permutations of string pat [ ] in string txt [ ] ; countp [ ] : store count of all characters of pattern counttw [ ] : store count of current window of text ; traverse through remaining characters of pattern ; compare counts of current window of text with counts of pattern [ ] ; cout << pat << " ▁ " << txt << " ▁ " ; ; add current character to current window ; remove the first character of previous window ; check for the last window in text ; function to return the number of sub - strings of s1 that are anagrams of any sub - string of s2 ; initializing variables ; outer loop for picking starting point ; loop for different length of substrings ; if s2 has any substring which is anagram of s1 . substr ( i , len ) ; increment the count ; 

ALL_CHARS = 256


def compare(arr1, arr2):
    for i in range(ALL_CHARS):
        if arr1[i] != arr2[i]:
            return False
    return True


def search(pat, txt):
    M = len(pat)
    N = len(txt)
    countP = [0] * ALL_CHARS
    countTW = [0] * ALL_CHARS
    for i in range(M):
        countP[ord(pat[i])] += 1
        countTW[ord(txt[i])] += 1
    for i in range(M, N):
        if compare(countP, countTW):
            return True
        countTW[ord(txt[i])] += 1
        countTW[ord(txt[i - M])] -= 1
    if compare(countP, countTW):
        return True
    return False


def calculateSubString(s1, s2, n):
    count, j, x = 0, 0, 0
    for i in range(n):
        for length in range(1, n - i + 1):
            if search(s1[i:i + length], s2):
                count += 1
    return count


if __name__ == "__main__":
    str1 = "PLEASEHELPIMTRAPPED"
    str2 = "INAKICKSTARTFACTORY"
    length = len(str1)
    print(calculateSubString(str1, str2, length))

# Expected output:
9
# sum of the alphabetical values of the characters of a string | function to find string score ; 
def strScore(str, s, n):
    score = 0
    index = 0
    for i in range(n):
        if (str[i] == s):
            for j in range(len(s)):
                score += (ord(s[j]) - ord('a') + 1)
            index = i + 1
            break
    score = score * index
    return score


str = ["sahil", "shashanak", "sanjit", "abhinav", "mohit"]
s = "abhinav"
n = len(str)
score = strScore(str, s, n)
print(score)

# Expected output:
228
# minimum swaps to group similar characters side by side ? | checks whether a string has similar characters side by side ; if similar chars side by side , continue ; if we have found a char equal to current char and does not exist side to it , return false ; counts min swap operations to convert a string that has similar characters side by side ; base case ; considering swapping of i and l chars ; backtrack ; not considering swapping of i and l chars ; taking min of above two ; 

from sys import maxsize


def sameCharAdj(string):
    n = len(string)
    st = set()
    st .add(string[0])
    for i in range(1, n):
        if string[i] == string[i - 1]:
            continue
        if string[i] in st:
            return False
        st .add(string[i])
    return True


def minSwaps(string, l, r, cnt, minm):
    if l == r:
        if sameCharAdj(string):
            return cnt
        else:
            return maxsize
    for i in range(l + 1, r + 1, 1):
        string[i], string[l] = string[l], string[i]
        cnt += 1
        x = minSwaps(string, l + 1, r, cnt, minm)
        string[i], string[l] = string[l], string[i]
        cnt -= 1
        y = minSwaps(string, l + 1, r, cnt, minm)
        minm = min(minm, min(x, y))
    return minm


if __name__ == "__main__":
    string = "abbaacb"
    string = list(string)
    n = len(string)
    cnt = 0
    minm = maxsize
    print(minSwaps(string, 0, n - 1, cnt, minm))

# Expected output:
2
# get k | function to return the k - th letter from new string . ; finding size = length of new string s ; get the k - th letter ; 
def K_thletter(S, K):

    N = len(S)
    size = 0

    for i in range(0, N):
        if S[i].isdigit():
            size = size * int(S[i])
        else:
            size += 1
    for i in range(N - 1, -1, -1):
        K %= size

        if K == 0 and S[i].isalpha():
            return S[i]

        if S[i].isdigit():
            size = size // int(S[i])
        else:
            size -= 1


if __name__ == "__main__":

    S = "geeks2for2"
    K = 15

    print(K_thletter(S, K))

# Expected output:
e
# minimum number of parentheses to be added to make it valid | function to return required minimum number ; maintain balance of string ; it is guaranteed bal >= - 1 ; 
def minParentheses(p):
    bal = 0
    ans = 0
    for i in range(0, len(p)):
        if (p[i] == '('):
            bal += 1
        else:
            bal += -1
        if (bal == -1):
            ans += 1
            bal += 1
    return bal + ans


if __name__ == '__main__':
    p = "())"
    print(minParentheses(p))

# Expected output:
1
# check if suffix and prefix of a string are palindromes | function to check whether the string is a palindrome ; reverse the string and assign it to new variable for comparison ; check if both are same ; function to check whether the string has prefix and suffix substrings of length greater than 1 which are palindromes . ; check all prefix substrings ; check if the prefix substring is a palindrome ; if we did not find any palindrome prefix of length greater than 1. ; check all suffix substrings , as the string is reversed now ; check if the suffix substring is a palindrome ; if we did not find a suffix ; 
def isPalindrome(r):
    p = r[::-1]
    return r == p


def CheckStr(s):
    l = len(s)
    i = 0
    for i in range(2, l + 1):
        if isPalindrome(s[0:i]):
            break
    if i == (l + 1):
        return False
    for i in range(2, l + 1):
        if isPalindrome(s[l - i:l]):
            return True
    return False


if __name__ == "__main__":
    s = "abccbarfgdbd"
    if CheckStr(s):
        print("YES")
    else:
        print("NO")

# Expected output:
YES
# rotations of a binary string with odd value | function to calculate total odd equivalent ; 
def oddEquivalent(s, n):
    count = 0
    for i in range(0, n):
        if (s[i] == '1'):
            count = count + 1
    return count


if __name__ == '__main__':
    s = "1011011"
    n = len(s)
    print(oddEquivalent(s, n))

# Expected output:
5
# minimum operation require to make first and last character same | python3 program to find minimum operation require to make first and last character same ; return the minimum operation require to make string first and last character same . ; store indexes of first occurrences of characters . ; initialize result ; traverse through all characters ; find first occurrence ; update result for subsequent occurrences ; 

MAX = 256


def minimumOperation(s):
    n = len(s)
    first_occ = [-1] * MAX
    res = float('inf')
    for i in range(0, n):
        x = s[i]
        if first_occ[ord(x)] == -1:
            first_occ[ord(x)] = i
        else:
            last_occ = n - i - 1
            res = min(res, first_occ[ord(x)] + last_occ)
    return res


if __name__ == "__main__":
    s = "bacdefghipalop"
    print(minimumOperation(s))

# Expected output:
4
# lexicographically smallest and largest substring of size k | python 3 program to find lexicographically largest and smallest substrings of size k . ; initialize min and max as first substring of size k ; consider all remaining substrings . we consider every substring ending with index i . ; print result . ; 
def getSmallestAndLargest(s, k):
    currStr = s[:k]
    lexMin = currStr
    lexMax = currStr
    for i in range(k, len(s)):
        currStr = currStr[1:k] + s[i]
        if (lexMax < currStr):
            lexMax = currStr
        if (lexMin > currStr):
            lexMin = currStr
    print(lexMin)
    print(lexMax)


if __name__ == '__main__':
    str1 = "GeeksForGeeks"
    k = 3
    getSmallestAndLargest(str1, k)

# Expected output:
For
sFo
# program to print the initials of a name with the surname | python program to print the initials of a name with the surname ; to remove any leading or trailing spaces ; to store extracted words ; forming the word ; when space is encountered it means the name is completed and thereby extracted ; printing the first letter of the name in capital letters ; for the surname , we have to print the entire surname and not just the initial string " t " has the surname now ; first letter of surname in capital letter ; rest of the letters in small ; printing surname ; 
def printInitials(string: str):
    length = len(string)
    string .strip()
    t = ""
    for i in range(length):
        ch = string[i]
        if ch != ' ':
            t += ch
        else:
            print(t[0].upper() + ". ", end="")
            t = ""
    temp = ""
    for j in range(len(t)):
        if j == 0:
            temp += t[0].upper()
        else:
            temp += t[j].lower()
    print(temp)


if __name__ == "__main__":
    string = "ishita bhuiya"
    printInitials(string)

# Expected output:
I. Bhuiya
# count of strings that can be formed from another string using each character at | python3 program to print the number of times str2 can be formed from str1 using the characters of str1 only once ; function to find the number of str2 that can be formed using characters of str1 ; iterate and mark the frequencies of all characters in str1 ; find the minimum frequency of every character in str1 ; 

import sys


def findNumberOfTimes(str1, str2):
    freq = [0] * 26
    l1 = len(str1)
    freq2 = [0] * 26
    l2 = len(str2)
    for i in range(l1):
        freq[ord(str1[i]) - ord("a")] += 1
    for i in range(l2):
        freq2[ord(str2[i]) - ord("a")] += 1
    count = sys .maxsize
    for i in range(l2):
        count = min(count, freq[ord(str2[i]) - ord('a')] /
                    freq2[ord(str2[i]) - ord('a')])
    return count


if __name__ == '__main__':
    str1 = "foreeksgekseg"
    str2 = "geeks"
    print(findNumberOfTimes(str1, str2))

# Expected output:
2.0
# string transformation using xor and or | function to check if conversion is possible or not ; if lengths are different ; iterate to check if both strings have 1 ; to check if there is even one 1 in string s1 ; to check if there is even one 1 in string s2 ; if both string do not have a '1' . ; 
def solve(s1, s2):
    flag1 = 0
    flag2 = 0
    if (len(s1) != len(s2)):
        return False
    l = len(s1)
    for i in range(0, l):
        if (s1[i] == '1'):
            flag1 = 1
        if (s2[i] == '1'):
            flag2 = 1
        if (flag1 & flag2):
            return True
        if (not flag1 and not flag2):
            return True
    return False


s1 = "100101"
s2 = "100000"
if solve(s1, s2):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# smallest alphabet greater than a given character | returns the smallest character from the given set of letters that is greater than k ; take the first element as l and the rightmost element as r ; if this while condition does not satisfy simply return the first element . ; return the smallest element ; 
def nextGreatestAlphabet(alphabets, K):
    n = len(alphabets)
    if (K >= alphabets[n - 1]):
        return alphabets[0]
    l = 0
    r = len(alphabets) - 1
    ans = -1
    while (l <= r):
        mid = int((l + r) / 2)
        if (alphabets[mid] > K):
            r = mid - 1
            ans = mid
        else:
            l = mid + 1
    if (alphabets[ans] < K):
        return alphabets[0]
    else:
        return alphabets[ans]


letters = ['A', 'r', 'z']
K = 'z'
result = nextGreatestAlphabet(letters, K)
print(result)

# Expected output:
A
# longest substring of 0 s in a string formed by k concatenations | function to calculate maximum length of substring containing only zero ; loop to calculate longest substring in string containing 0 's ; if all elements in string a are '0 ; else , find prefix and suffix containing only zeroes ; calculate length of the prefix containing only zeroes ; calculate length of the suffix containing only zeroes ; if k <= 1 , no need to take suffix + prefix into account ; 
def subzero(str, k):
    ans = 0
    curr = 0
    n = len(str)
    for i in str:
        if (i == '0'):
            curr += 1

        else:
            curr = 0
        ans = max(ans, curr)
    if (ans == n):
        print(n * k)
        return
    else:
        pre = suff = 0

        for i in str:
            if (i == '0'):
                pre += 1
            else:
                break
        for i in range(n-1, -1, -1):
            if (str[i] == '0'):
                suff += 1
            else:
                break
    if (k > 1):
        ans = max(ans, pre + suff)
    print(ans)
    return


k = 5
str = '00100110'
subzero(str, k)

# Expected output:
3
# number of substrings of a string | python3 program to count number of substrings of a string ; 
def countNonEmptySubstr(str):
    n = len(str)
    return int(n * (n + 1) / 2)


s = "abcde"
print(countNonEmptySubstr(s))

# Expected output:
15
# count substrings with each character occurring at most k times | python 3 program to count number of substrings in which each character has count less than or equal to k . ; variable to store count of substrings . ; array to store count of each character . ; increment character count ; check only the count of current character because only the count of this character is changed . the ending point is incremented to current position only if all other characters have count at most k and hence their count is not checked . if count is less than k , then increase ans by 1. ; if count is less than k , then break as subsequent substrings for this starting point will also have count greater than k and hence are reduntant to check . ; return the final count of substrings . ; 
def findSubstrings(s, k):
    ans = 0
    n = len(s)
    for i in range(n):
        cnt = [0] * 26
        for j in range(i, n):
            cnt[ord(s[j]) - ord('a')] += 1
            if (cnt[ord(s[j]) - ord('a')] <= k):
                ans += 1
            else:
                break
    return ans


if __name__ == "__main__":
    S = "aaabb"
    k = 2
    print(findSubstrings(S, k))

# Expected output:
12
# check if characters of one string can be swapped to form other | python3 program to check if characters of one string can be swapped to form other ; if length is not same print no ; count frequencies of character in first string . ; iterate through the second string decrement counts of characters in second string ; since lengths are same , some value would definitely become negative if result is false . ; 

MAX = 26


def targetstring(str1, str2):
    l1 = len(str1)
    l2 = len(str2)
    if (l1 != l2):
        return False
    map = [0] * MAX
    for i in range(l1):
        map[ord(str1[i]) - ord('a')] += 1
    for i in range(l2):
        map[ord(str2[i]) - ord('a')] -= 1
        if (map[ord(str2[i]) - ord('a')] < 0):
            return False
    return True


if __name__ == "__main__":
    str1 = "geeksforgeeks"
    str2 = "geegeeksksfor"
    if (targetstring(str1, str2)):
        print("YES")
    else:
        print("NO")

# Expected output:
YES
# find the number which contain the digit d | returns true if d is present as digit in number x . ; breal loop if d is present as digit ; if loop broke ; function to display the values ; check all numbers one by one ; checking for digit ; 
def isDigitPresent(x, d):
    while (x > 0):
        if (x % 10 == d):
            break
        x = x / 10
    return (x > 0)


def printNumbers(n, d):
    for i in range(0, n + 1):
        if (i == d or isDigitPresent(i, d)):
            print(i, end=" ")


n = 47
d = 7
print("The number of values are")
printNumbers(n, d)

# Expected output:
The number of values are
7 17 27 37 47
# find one extra character in a string | python3 program to find extra character in one string ; store string values in map ; store second string in map with frequency ; store first string in map with frequency ; if the frequency is 1 then this character is which is added extra ; 
def findExtraCharacter(strA, strB):
    m1 = {}
    for i in strB:
        if i in m1:
            m1[i] += 1
        else:
            m1[i] = 1
    for i in strA:
        m1[i] -= 1
    for h1 in m1:
        if m1[h1] == 1:
            return h1


if __name__ == "__main__":
    strA = 'abcd'
    strB = 'cbdad'
    print(findExtraCharacter(strA, strB))

# Expected output:
d
# find one extra character in a string | python 3 program to find extra character in one string ; result store the result ; traverse string a till end and xor with res ; xor with res ; traverse string b till end and xor with res ; xor with res ; print result at the end ; 
def findExtraCharcter(strA, strB):
    res = 0
    for i in range(0, len(strA)):
        res = res ^ (ord)(strA[i])
    for i in range(0, len(strB)):
        res = res ^ (ord)(strB[i])
    return ((chr)(res))


strA = "abcd"
strB = "cbdad"
print(findExtraCharcter(strA, strB))

# Expected output:
d
# find one extra character in a string | python program to find extra character in one string ; determine string with extra character ; add character codes of both the strings ; add last character code of large string ; minus the character code of smaller string from the character code of large string the result will be the extra character code ; 
def findExtraCharacter(s1, s2):
    smallStr = ""
    largeStr = ""
    if (len(s1) > len(s2)):
        smallStr = s2
        largeStr = s1
    else:
        smallStr = s1
        largeStr = s2
    smallStrCodeTotal = 0
    largeStrCodeTotal = 0
    i = 0
    while (i < len(smallStr)):
        smallStrCodeTotal += ord(smallStr[i])
        largeStrCodeTotal += ord(largeStr[i])
        i += 1
    largeStrCodeTotal += ord(largeStr[i])
    intChar = largeStrCodeTotal - smallStrCodeTotal
    return chr(intChar)


s1 = "abcd"
s2 = "cbdae"
extraChar = findExtraCharacter(s1, s2)
print("Extra Character:", extraChar)

# Expected output:
Extra Character: e
# evaluate an array expression with numbers , + and | function to find the sum of given array ; if string is empty ; stoi function to convert string into integer ; stoi function to convert string into integer ; find operator ; if operator is equal to ' + ' , add value in sum variable else subtract ; 
def calculateSum(arr, n):
    if (n == 0):
        return 0
    s = arr[0]
    value = int(s)
    sum = value
    for i in range(2, n, 2):
        s = arr[i]
        value = int(s)
        operation = arr[i - 1][0]
        if (operation == '+'):
            sum += value
        else:
            sum -= value
    return sum


arr = ["3", "+", "4", "-", "7", "+", "13"]
n = len(arr)
print(calculateSum(arr, n))

# Expected output:
13
# string with maximum number of unique characters | function to find string with maximum number of unique characters . ; index of string with maximum unique characters ; iterate through all strings ; array indicating any alphabet included or not included ; count number of unique alphabets in each string ; keep track of maximum number of alphabets ; print result ; 
def LargestString(na):
    N = len(na)
    c = [0] * N
    m = 0
    for j in range(N):
        character = [False] * 26
        for k in range(len(na[j])):
            x = ord(na[j][k]) - ord('A')
            if ((na[j][k] != ' ') and (character[x] == False)):
                c[j] += 1
                character[x] = True
            if (c[j] > c[m]):
                m = j
    print(na[m])


na = ["BOB", "A AB C JOHNSON", "ANJALI", "ASKRIT", "ARMAN MALLIK"]
LargestString(na)

# Expected output:
A AB C JOHNSON
# program for length of the longest word in a sentence | python program to find the number of characters in the longest word in the sentence . ; 
def longestWordLength(string):
    length = 0
    for word in string .split():
        if (len(word) > length):
            length = len(word)
    return length


string = "I am an intern at geeksforgeeks"
print(longestWordLength(string))

# Expected output:
13