giulio98/xlcost-single-prompt huggingface dataset:
# check the divisibility of hexadecimal numbers | python3 implementation of the approach ; function that returns true if s is divisible by m ; map to map characters to real value ; to store the remainder at any stage ; find the remainder ; check the value of remainder ; 

CHARS = "0123456789ABCDEF"
DIGITS = 16


def isDivisible(s, m):
    mp = dict .fromkeys(CHARS, 0)
    for i in range(DIGITS):
        mp[CHARS[i]] = i
    r = 0
    for i in range(len(s)):
        r = (r * 16 + mp[s[i]]) % m
    if (not r):
        return True
    return False


if __name__ == "__main__":
    s = "10"
    m = 3
    if (isDivisible(s, m)):
        print("Yes")
    else:
        print("No")

# Expected output:
No
# maximum number of splits of a binary number | function to return the required count ; if the splitting is not possible ; to store the count of zeroes ; counting the number of zeroes ; return the final answer ; 
def cntSplits(s):
    if (s[len(s) - 1] == '1'):
        return -1
    ans = 0
    for i in range(len(s)):
        ans += (s[i] == '0')
    return ans


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

# Expected output:
3
# modify the string such that every character gets replaced with the next character in the keyboard | python3 implementation of the approach ; function to return the modified string ; map to store the next character on the keyboard for every possible lowercase character ; update the string ; 

CHARS = "qwertyuiopasdfghjklzxcvbnm"
MAX = 26


def getString(string, n):
    string = list(string)
    uMap = {}
    for i in range(MAX):
        uMap[CHARS[i]] = CHARS[(i + 1) % MAX]
    for i in range(n):
        string[i] = uMap[string[i]]
    return "".join(string)


if __name__ == "__main__":
    string = "geeks"
    n = len(string)
    print(getString(string, n))

# Expected output:
hrrld
# queries to find the count of characters preceding the given location | python 3 implementation of the approach ; returns character at index pos - 1 ; 
def Count(s, pos):
    c = s[pos - 1]
    counter = 0
    for i in range(pos - 1):
        if s[i] == c:
            counter = counter + 1
    return counter


if __name__ == "__main__":
    s = "abacsddaa"
    n = len(s)
    query = [9, 3, 2]
    Q = len(query)
    for i in range(Q):
        pos = query[i]
        print(Count(s, pos))

# Expected output:
3
1
0
# count of matchsticks required to represent the given number | stick [ i ] stores the count of sticks required to represent the digit i ; function to return the count of matchsticks required to represent the given number ; for every digit of the given number ; add the count of sticks required to represent the current digit ; 

sticks = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]


def countSticks(string, n):
    cnt = 0
    for i in range(n):
        cnt += (sticks[ord(string[i]) - ord('0')])
    return cnt


if __name__ == "__main__":
    string = "56"
    n = len(string)
    print(countSticks(string, n))

# Expected output:
11
# modulo of a large binary string | function to return the value of ( str % k ) ; pwrtwo [ i ] will store ( ( 2 ^ i ) % k ) ; to store the result ; if current bit is 1 ; add the current power of 2 ; 
def getMod(_str, n, k):
    pwrTwo = [0] * n
    pwrTwo[0] = 1 % k
    for i in range(1, n):
        pwrTwo[i] = pwrTwo[i - 1] * (2 % k)
        pwrTwo[i] %= k
    res = 0
    i = 0
    j = n - 1
    while (i < n):
        if (_str[j] == '1'):
            res += (pwrTwo[i])
            res %= k
        i += 1
        j -= 1
    return res


_str = "1101"
n = len(_str)
k = 45
print(getMod(_str, n, k))

# Expected output:
13
# count number of binary strings such that there is no substring of length greater than or equal to 3 with all 1 's | python3 implementation of the approach ; function to return the count of all possible valid strings ; initialise and fill 0 's in the dp array ; base cases ; dp [ i ] [ j ] = number of possible strings such that '1' just appeared consecutively j times upto the ith index ; taking previously calculated value ; taking all possible cases that can appear at the nth position ; 

MOD = 1000000007


def countStrings(N):
    dp = [[0] * 3 for i in range(N + 1)]
    dp[1][0] = 1
    dp[1][1] = 1
    dp[1][2] = 0
    for i in range(2, N + 1):
        dp[i][0] = (dp[i - 1][0] + dp[i - 1][1] + dp[i - 1][2]) % MOD
        dp[i][1] = dp[i - 1][0] % MOD
        dp[i][2] = dp[i - 1][1] % MOD
    ans = (dp[N][0] + dp[N][1] + dp[N][2]) % MOD
    return ans


if __name__ == '__main__':
    N = 3
    print(countStrings(N))

# Expected output:
7
# find the maximum possible binary number from given string | function to return maximum number that can be formed from the string ; to store the frequency of ' z ' and ' n ' in the given string ; number of zeroes ; number of ones ; to store the required number ; add all the ones ; add all the zeroes ; 
def maxNumber(string, n):
    freq = [0, 0]
    for i in range(n):
        if (string[i] == 'z'):
            freq[0] += 1
        elif (string[i] == 'n'):
            freq[1] += 1
    num = ""
    for i in range(freq[1]):
        num += '1'
    for i in range(freq[0]):
        num += '0'
    return num


if __name__ == "__main__":
    string = "roenenzooe"
    n = len(string)
    print(maxNumber(string, n))

# Expected output:
110
# find the occurrence of the given binary pattern in the binary representation of the array elements | function to return the binary representation of n ; array to store binary representation ; counter for binary array ; storing remainder in binary array ; to store the binary representation as a string ; function to return the frequency of pat in the given txt ; a loop to slide pat [ ] one by one ; for current index i , check for pattern match ; if pat [ 0. . . m - 1 ] = txt [ i , i + 1 , ... i + m - 1 ] ; function to find the occurrence of the given pattern in the binary representation of elements of arr [ ] ; for every element of the array ; find its binary representation ; print the occurrence of the given pattern in its binary representation ; 
def decToBinary(n):
    binaryNum = [0 for i in range(32)]
    i = 0
    while (n > 0):
        binaryNum[i] = n % 2
        n = n // 2
        i += 1
    binary = ""
    for j in range(i - 1, -1, -1):
        binary += str(binaryNum[j])
    return binary


def countFreq(pat, txt):
    M = len(pat)
    N = len(txt)
    res = 0
    for i in range(N - M + 1):
        j = 0
        while (j < M):
            if (txt[i + j] != pat[j]):
                break
            j += 1
        if (j == M):
            res += 1
            j = 0
    return res


def findOccurrence(arr, n, pattern):
    for i in range(n):
        binary = decToBinary(arr[i])
        print(countFreq(pattern, binary), end=" ")


arr = [5, 106, 7, 8]
pattern = "10"
n = len(arr)
findOccurrence(arr, n, pattern)

# Expected output:
1 3 0 1
# check if the bracket sequence can be balanced with at most one change in the position of a bracket | function that returns true if the sequence can be balanced by changing the position of at most one bracket ; odd length string can never be balanced ; add ' ( ' in the beginning and ' ) ' in the end of the string ; if its an opening bracket then append it to the temp string ; if its a closing bracket ; there was an opening bracket to match it with ; no opening bracket to match it with ; sequence is balanced ; 
def canBeBalanced(s, n):
    if n % 2 == 1:
        return False
    k = "("
    k = k + s + ")"
    d = []
    count = 0
    for i in range(len(k)):
        if k[i] == "(":
            d .append("(")
        else:
            if len(d) != 0:
                d .pop()
            else:
                return False
    if len(d) == 0:
        return True
    return False


S = ")(()"
n = len(S)
if (canBeBalanced(S, n)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# find the winner of the game | function to find the winner of the game ; to store the strings for both the players ; if the index is even ; append the current character to player a 's string ; if the index is odd ; append the current character to player b 's string ; sort both the strings to get the lexicographically smallest string possible ; copmpare both the strings to find the winner of the game ; 
def find_winner(string, n):
    string1 = ""
    string2 = ""
    for i in range(n):
        if (i % 2 == 0):
            string1 += string[i]
        else:
            string2 += string[i]
    string1 = "".join(sorted(string1))
    string2 = "".join(sorted(string2))
    if (string1 < string2):
        print("A", end="")
    elif (string2 < string1):
        print("B", end="")
    else:
        print("Tie", end="")


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

# Expected output:
B
# count of characters in str1 such that after deleting anyone of them str1 becomes str2 | function to return the count of required indices ; solution doesn 't exist ; find the length of the longest common prefix of strings ; find the length of the longest common suffix of strings ; if solution does not exist ; return the count of indices ; 
def Find_Index(str1, str2):
    n = len(str1)
    m = len(str2)
    l = 0
    r = 0
    if (n != m + 1):
        return -1
    for i in range(m):
        if str1[i] == str2[i]:
            l += 1
        else:
            break
    i = n - 1
    j = m - 1
    while i >= 0 and j >= 0 and str1[i] == str2[j]:
        r += 1
        i -= 1
        j -= 1
    if l + r < m:
        return -1
    else:
        i = max(n - r, 1)
        j = min(l + 1, n)
        return (j - i + 1)


if __name__ == "__main__":
    str1 = "aaa"
    str2 = "aa"
    print(Find_Index(str1, str2))

# Expected output:
3
# expand the string according to the given conditions | function to expand and print the given string ; subtract '0' to convert char to int ; characters within brackets ; expanding ; reset the variables ; 
def expandString(strin):
    temp = ""
    j = 0
    i = 0
    while (i < len(strin)):
        if (strin[i] >= "0"):
            num = ord(strin[i]) - ord("0")
            if (strin[i + 1] == '('):
                j = i + 1
                while (strin[j] != ')'):
                    if ((strin[j] >= 'a' and strin[j] <= 'z') or (
                            strin[j] >= 'A' and strin[j] <= 'Z')):
                        temp += strin[j]
                    j += 1
                for k in range(1, num + 1):
                    print(temp, end="")
                num = 0
                temp = ""
                if (j < len(strin)):
                    i = j
        i += 1


strin = "3(ab)4(cd)"
expandString(strin)

# Expected output:
abababcdcdcdcd
# largest substring of str2 which is a prefix of str1 | python3 implementation of the approach ; function to return the largest substring in str2 which is a prefix of str1 ; to store the index in str2 which matches the prefix in str1 ; while there are characters left in str1 ; if the prefix is not found in str2 ; remove the last character ; prefix found ; no substring found in str2 that matches the prefix of str1 ; 

import operator


def findPrefix(str1, str2):
    pos = False
    while (len(str1) != 0):
        if operator .contains(str2, str1) != True:
            str1 = str1[0:len(str1) - 1]
        else:
            pos = operator .contains(str2, str1)
            break
    if (pos == False):
        return "-1"
    return str1


if __name__ == '__main__':
    str1 = "geeksfor"
    str2 = "forgeeks"
    print(findPrefix(str1, str2))

# Expected output:
geeks
# round the given number to nearest multiple of 10 | set | function to round the given number to the nearest multiple of 10 ; if string is empty ; if the last digit is less then or equal to 5 then it can be rounded to the nearest ( previous ) multiple of 10 by just replacing the last digit with 0 ; set the last digit to 0 ; print the updated number ; the number hast to be rounded to the next multiple of 10 ; to store the carry ; replace the last digit with 0 ; starting from the second last digit , add 1 to digits while there is carry ; while there are digits to consider and there is carry to add ; get the current digit ; add the carry ; if the digit exceeds 9 then the carry will be generated ; else there will be no carry ; update the current digit ; get to the previous digit ; if the carry is still 1 then it must be inserted at the beginning of the string ; prin the rest of the number ; 
def roundToNearest(str, n):
    if (str == ""):
        return
    if (ord(str[n - 1]) - ord('0') <= 5):
        str = list(str)
        str[n - 1] = '0'
        str = ''.join(str)
        print(str[0:n])
    else:
        carry = 0
        str = list(str)
        str[n - 1] = '0'
        str = ''.join(str)
        i = n - 2
        carry = 1
        while (i >= 0 and carry == 1):
            currentDigit = ord(str[i]) - ord('0')
            currentDigit += carry
            if (currentDigit > 9):
                carry = 1
                currentDigit = 0
            else:
                carry = 0
            str[i] = chr(currentDigit + '0')
            i -= 1
        if (carry == 1):
            print(carry)
        print(str[0:n])


if __name__ == '__main__':
    str = "99999999999999993"
    n = len(str)
    roundToNearest(str, n)

# Expected output:
99999999999999990
# repeat substrings of the given string required number of times | function that returns true if the passed character is a digit ; function to return the next index of a non - digit character in the string starting at the index i ( returns - 1 ifno such index is found ) ; if the character at index i is a digit then skip to the next character ; if no such index was found ; function to append str the given number of times to the stringbuilder ; function to return the string after performing the given operations ; to build the resultant string ; index of the first non - digit character in the string ; while there are substrings that do not consist of digits ; find the ending of the substring ; starting index of the number ; if no digit appears after the current substring ; find the index at which the current number ends ; parse the number from the substring ; repeat the current substring required number of times ; find the next non - digit character index ; return the resultant string ; 
def isDigit(ch):
    if ch >= '0' and ch <= '9':
        return True
    return False


def nextNonDigit(string, i):
    while i < len(string) and isDigit(string[i]):
        i += 1
    if i >= len(string):
        return -1
    return i


def appendRepeated(sb, string, times):
    for i in range(times):
        sb .append(string)


def findString(string, n):
    sb = list()
    startStr = nextNonDigit(string, 0)
    while startStr != -1:
        endStr = startStr
        while (endStr + 1 < n and not isDigit(string[endStr + 1])):
            endStr += 1
        startNum = endStr + 1
        if startNum == -1:
            break
        endNum = startNum
        while (endNum + 1 < n and isDigit(string[endNum + 1])):
            endNum += 1
        num = int(string[startNum:endNum + 1])
        appendRepeated(sb, string[startStr:endStr + 1], num)
        startStr = nextNonDigit(string, endStr + 1)
    sb = ''.join(sb)
    return sb


if __name__ == "__main__":
    string = "g1ee1ks1for1g1e2ks1"
    n = len(string)
    print(findString(string, n))

# Expected output:
geeksforgeeks
# check if the given string is vowel prime | function that returns true if c is a vowel ; function that returns true if all the vowels in the given string are only at prime indices ; create a boolean array " prime [ 0 . . n ] " and initialize all entries in it as true . a value in prime [ i ] will finally be false if i is not a prime , else true . ; 0 and 1 are not prime ; if prime [ p ] is not changed , then it is a prime ; update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; for every character of the given string ; if current character is vowel and the index is not prime ; 
def isVowel(c):
    if (c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u'):
        return True
    return False


def isVowelPrime(Str, n):
    prime = [True for i in range(n)]
    prime[0] = False
    prime[1] = False
    for p in range(2, n):
        if p * p > n:
            break
        if (prime[p]):
            for i in range(2 * p, n, p):
                prime[i] = False
    for i in range(n):
        if (isVowel(Str[i]) and prime[i] == False):
            return False
    return True


Str = "geeksforgeeks"
n = len(Str)
if (isVowelPrime(Str, n)):
    print("Yes")
else:
    print("No")

# Expected output:
No
# swap all occurrences of two characters to get lexicographically smallest string | python3 implementation of the approach ; function to return the lexicographically smallest after swapping all the occurrences of any two characters ; to store the first index of every character of str ; store the first occurring index every character ; if current character is appearing for the first time in str ; starting from the leftmost character ; for every character smaller than ord ( str [ i ] ) ; if there is a character in str which is smaller than ord ( str [ i ] ) and appears after it ; if the required character pair is found ; if swapping is possible ; characters to be swapped ; for every character ; replace every ch1 with ch2 and every ch2 with ch1 ; 

MAX = 256


def smallestStr(str, n):
    i, j = 0, 0
    chk = [0 for i in range(MAX)]
    for i in range(MAX):
        chk[i] = -1
    for i in range(n):
        if (chk[ord(str[i])] == -1):
            chk[ord(str[i])] = i
    for i in range(n):
        flag = False
        for j in range(ord(str[i])):
            if (chk[j] > chk[ord(str[i])]):
                flag = True
                break
        if (flag):
            break
    if (i < n):
        ch1 = (str[i])
        ch2 = chr(j)
        for i in range(n):
            if (str[i] == ch1):
                str[i] = ch2
            elif (str[i] == ch2):
                str[i] = ch1
    return "".join(str)


st = "ccad"
str = [i for i in st]
n = len(str)
print(smallestStr(str, n))

# Expected output:
aacd
# longest sub string of 0 's in a binary string which is repeated k times | function to find the longest subof 0 's ; to store size of the string ; to store the required answer ; find the longest subof 0 's ; run a loop upto s [ i ] is zero ; check the conditions ; 
def longest_substring(s, k):
    n = len(s)
    if (k > 1):
        s += s
        n *= 2
    ans = 0
    i = 0
    while (i < n):
        x = 0
        while (i < n and s[i] == '0'):
            x, i = x + 1, i + 1
        ans = max(ans, x)
        i += 1
    if (k == 1 or ans != n):
        return ans
    else:
        return (ans // 2) * k


s = "010001000"
k = 4
print(longest_substring(s, k))

# Expected output:
4
# find the number of occurrences of a character upto preceding position | function to find the number of occurrences of a character at position p upto p - 1 ; return the required count ; 
def Occurrence(s, position):
    count = 0
    for i in range(position - 1):
        if (s[i] == s[position - 1]):
            count += 1
    return count


s = "ababababab"
p = 9
print(Occurrence(s, p))

# Expected output:
4
# find the number of occurrences of a character upto preceding position | function to find the number of occurrences of a character at position p upto p - 1 ; iterate over the string ; store the occurrence of same character ; increase its frequency ; return the required count ; 
def countOccurrence(s, position):
    alpha = [0] * 26
    b = [0] * len(s)
    for i in range(0, len(s)):
        b[i] = alpha[ord(s[i]) - 97]
        alpha[ord(s[i]) - 97] = alpha[ord(s[i]) - 97] + 1
    return b[position - 1]


s = "ababababab"
p = 9
print(countOccurrence(s, p))

# Expected output:
4
# map every character of one string to another such that all occurrences are mapped to the same character | python 3 implementation of the approach ; function that returns true if the mapping is possible ; both the strings are of un - equal lengths ; to store the frequencies of the characters in both the string ; update frequencies of the characters ; for every character of s1 ; if current character is not present in s1 ; find a character in s2 that has frequency equal to the current character 's  frequency in s1 ; if such character is found ; set the frequency to - 1 so that it doesn 't get picked again ; set found to true ; if there is no character in s2 that could be mapped to the current character in s1 ; 

MAX = 26


def canBeMapped(s1, l1, s2, l2):
    if (l1 != l2):
        return False
    freq1 = [0 for i in range(MAX)]
    freq2 = [0 for i in range(MAX)]
    for i in range(l1):
        freq1[ord(s1[i]) - ord('a')] += 1
    for i in range(l2):
        freq2[ord(s2[i]) - ord('a')] += 1
    for i in range(MAX):
        if (freq1[i] == 0):
            continue
        found = False
        for j in range(MAX):
            if (freq1[i] == freq2[j]):
                freq2[j] = -1
                found = True
                break
        if (found == False):
            return False
    return True


if __name__ == '__main__':
    s1 = "axx"
    s2 = "cbc"
    l1 = len(s1)
    l2 = len(s2)
    if (canBeMapped(s1, l1, s2, l2)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# generate all possible strings such that char at index i is either str1 [ i ] or str2 [ i ] | recursive function to generate the required strings ; if length of the current string is equal to the length of the given strings then the current string is part of the result ; choosing the current character from the string a ; choosing the current character from the string b ; 
def generateStr(a, b, s, count, len):
    if (count == len):
        print(s)
        return
    generateStr(a[1:], b[1:], s + a[0], count + 1, len)
    generateStr(a[1:], b[1:], s + b[0], count + 1, len)


a = "abc"
b = "def"
n = len(a)
generateStr(a, b, "", 0, n)

# Expected output:
abc
abf
aec
aef
dbc
dbf
dec
def
# program to generate all possible valid ip addresses from given string | set 2 | function to get all the valid ip - addresses ; if index greater than givenstring size and we have four block ; remove the last dot ; add ip - address to the results ; to add one index to ip - address ; select one digit and call the same function for other blocks ; backtrack to generate another possible ip address so we remove two index ( one for the digit and other for the dot ) from the end ; select two consecutive digits and call the same function for other blocks ; backtrack to generate another possible ip address so we remove three index from the end ; select three consecutive digits and call the same function for other blocks ; backtrack to generate another possible ip address so we remove four index from the end ; 
def GetAllValidIpAddress(result, givenString, index, count, ipAddress):
    if (len(givenString) == index and count == 4):
        ipAddress .pop()
        result .append(ipAddress)
        return
    if (len(givenString) < index + 1):
        return
    ipAddress = (ipAddress + givenString[index:index + 1] + ['.'])
    GetAllValidIpAddress(result, givenString, index + 1, count + 1, ipAddress)
    ipAddress = ipAddress[:-2]
    if (len(givenString) < index + 2 or givenString[index] == '0'):
        return
    ipAddress = ipAddress + givenString[index:index + 2] + ['.']
    GetAllValidIpAddress(result, givenString, index + 2, count + 1, ipAddress)
    ipAddress = ipAddress[:-3]
    if (len(givenString) < index +
            3 or int("".join(givenString[index:index + 3])) > 255):
        return
    ipAddress += givenString[index:index + 3] + ['.']
    GetAllValidIpAddress(result, givenString, index + 3, count + 1, ipAddress)
    ipAddress = ipAddress[:-4]


if __name__ == "__main__":
    givenString = list("25525511135")
    result = []
    GetAllValidIpAddress(result, givenString, 0, 0, [])
    for i in range(len(result)):
        print("".join(result[i]))

# Expected output:
255.255.11.135
255.255.111.35