giulio98/xlcost-single-prompt huggingface dataset:
# count of palindromic strings of size upto n consisting of first k alphabets occurring at most twice | function of return the number of palindromic strings of length n with first k alphabets possible ; if n is odd , half + 1 position can be filled to cope with the extra middle element ; k is reduced by one , because count of choices for the next position is reduced by 1 as a element can only once ; return the possible count ; function to find the count of palindromic string of first k characters according to the given criteria ; if n = 1 , then only k palindromic strings possible . ; if n = 2 , the 2 * k palindromic strings possible , k for n = 1 and k for n = 2 ; initialize ans with the count of strings possible till n = 2 ; return the possible count ; 
def lengthNPalindrome(N, K):
    half = N // 2
    if (N & 1):
        half += 1
    ans = 1
    for i in range(1, half + 1):
        ans *= K
        K -= 1
    return ans


def palindromicStrings(N, K):
    if (N == 1):
        return K
    if (N == 2):
        return 2 * K
    ans = 0
    ans += (2 * K)
    for i in range(3, N + 1):
        ans += lengthNPalindrome(i, K)
    return ans


if __name__ == "__main__":
    N = 4
    K = 3
    print(palindromicStrings(N, K))

# Expected output:
18
# minimum number of characters required to be added to a string such that all lowercase alphabets occurs as a subsequence in increasing order | python3 program for the above approach ; function to find the lcs of strings s and string t ; base case ; already calculated state ; if the characters are the same ; otherwise ; function to find the minimum number of characters that needs to be appended in the string to get all lowercase alphabets as a subsequences ; string containing all the characters ; stores the result of overlapping subproblems ; return the minimum characters required ; 

import numpy as np


def LCS(S, N, T, M, dp):
    if (N == 0 or M == 0):
        return 0
    if (dp[N][M] != 0):
        return dp[N][M]
    if (S[N - 1] == T[M - 1]):
        dp[N][M] = 1 + LCS(S, N - 1, T, M - 1, dp)
        return dp[N][M]
    dp[N][M] = max(LCS(S, N - 1, T, M, dp), LCS(S, N, T, M - 1, dp))
    return dp[N][M]


def minimumCharacter(S):
    T = "abcdefghijklmnopqrstuvwxyz"
    N = len(S)
    M = len(T)
    dp = np .zeros((N + 1, M + 1))
    return (26 - LCS(S, N, T, M, dp))


if __name__ == "__main__":
    S = "abcdadc"
    print(minimumCharacter(S))

# Expected output:
22.0
# count ways to make the number formed by k concatenations of a numeric string divisible by 5 | python program for the above approach ; function to find the value of a ^ b modulo 1000000007 ; stores the resultant value a ^ b ; find the value of a ^ b ; function to count the number of ways such that the formed number is divisible by 5 by removing digits ; stores the count of ways ; find the count for string s ; if the digit is 5 or 0 ; find the count of string for k concatenation of string s ; find the total count ; 

MOD = 1000000007


def exp_mod(a, b):
    ret = 1
    while (b):
        if (b & 1):
            ret = ret * a % MOD
        b >>= 1
        a = a * a % MOD
    return ret


def countOfWays(s, k):
    N = len(s)
    ans = 0
    for i in range(N):
        if (s[i] == '5' or s[i] == '0'):
            ans = (ans + exp_mod(2, i)) % MOD
    q = exp_mod(2, N)
    qk = exp_mod(q, k)
    inv = exp_mod(q - 1, MOD - 2)
    ans = ans * (qk - 1) % MOD
    ans = ans * inv % MOD
    return ans


S = "1256"
K = 1
print(countOfWays(S, K))

# Expected output:
4
# find the string present at the middle of a lexicographically increasing sequence of strings from s to t | function to print the string at the middle of lexicographically increasing sequence of strings from s to t ; stores the base 26 digits after addition ; iterete from right to left and add carry to next position ; reduce the number to find the middle string by dividing each position by 2 ; if current value is odd , carry 26 to the next index value ; 
def printMiddleString(S, T, N):
    a1 = [0] * (N + 1)
    for i in range(N):
        a1[i + 1] = ord(S[i]) - ord("a") + ord(T[i]) - ord("a")
    for i in range(N, 1, -1):
        a1[i - 1] += a1[i] // 26
        a1[i] %= 26
    for i in range(N + 1):
        if (a1[i] & 1):
            if (i + 1 <= N):
                a1[i + 1] += 26
        a1[i] = a1[i] // 2
    for i in range(1, N + 1):
        print(chr(a1[i] + ord("a")), end="")
    return 0


N = 5
S = "afogk"
T = "asdji"
printMiddleString(S, T, N)

# Expected output:
alvuw
# find character at kth index by appending s1 ( m ) times and s2 ( m + 1 ) times | python program to solve the above approach ; initializing first and second variable as to store how many string ' s ' and string ' t ' will be appended ; storing tmp length ; if length of string tmp is greater than k , then we have reached our destination string now we can return character at index k ; appending s to tmp , f times ; appending t to tmp , s times ; extracting output character ; 
def KthCharacter(s, t, k):
    f = 1
    ss = 2
    tmp = ""
    lenn = len(tmp)
    while (lenn < k):
        tf = f
        ts = ss
        while (tf != 0):
            tf -= 1
            tmp += s
        while (ts != 0):
            ts -= 1
            tmp += t
        f += 2
        ss += 2
        lenn = len(tmp)
    output = tmp[k - 1]
    return output


S1 = "a"
S2 = "bc"
k = 4
ans = KthCharacter(S1, S2, k)
print(ans)

# Expected output:
b
# find character at kth index by appending s1 ( m ) times and s2 ( m + 1 ) times | python program to solve the above approach ; storing length ; variables for temporary strings of s and t ; final output variable ; if k is greater than even after adding string ' s ' ' first ' times ( let ' s ▁ call ▁ it ▁ x ) ▁ we ' ll subtract x from k ; incrementing first by 2 , as said in problem statement ; if k is greater than even after adding string ' t ' ' second ' times ( let ' s ▁ call ▁ it ▁ y ) ▁ we ' ll subtract y from k ; incrementing second by two as said in problem statement ; if k is smaller than y , then the character will be at position k % m . ; returning character at k index ; if k is smaller than x , then the character is at position k % n ; returning character at k index ; 
def KthCharacter(s, t, k):
    n = len(s)
    m = len(t)
    first = 1
    second = 2
    output = '?'
    while (k > 0):
        if (k > first * n):
            x = first * n
            k = k - x
            first = first + 2
            if (k > second * m):
                y = second * m
                k = k - y
                second = second + 2
            else:
                ind = k % m
                ind -= 1
                if (ind < 0):
                    ind = m - 1
                output = t[ind]
                break
        else:
            ind = k % n
            ind -= 1
            if (ind < 0):
                ind = n - 1
            output = s[ind]
            break
    return output


S1 = "a"
S2 = "bc"
k = 4
ans = KthCharacter(S1, S2, k)
print(ans)

# Expected output:
b
# count of ways to rearrange n digits and m alphabets keeping all alphabets together | python program of the above approach ; function to find the factorial of the given number ; function to count ways to rearrange characters of the string such that all alphabets are adjacent . ; stores factorial of ( n + 1 ) ; stores factorial of ; 

import math


def fact(a):
    return math .factorial(a)


def findComb(N, M):
    x = fact(N + 1)
    y = fact(M)
    return (x * y)


if __name__ == "__main__":
    N = 2
    M = 2
    print(findComb(N, M))

# Expected output:
12
# count of camel case characters present in a given string | function to count all the camelcase characters in the string s ; stores the total count of camelcase characters ; traverse the string s ; if ascii value of character lies over the range [ 65 , 91 ] then increment the count ; print the total count obtained ; 
def countCamelCase(S):
    count = 0
    for i in range(len(S)):
        if (ord(S[i]) >= 65 and ord(S[i]) <= 91):
            count += 1
    print(count)


if __name__ == '__main__':
    S = "ckjkUUYII"
    countCamelCase(S)

# Expected output:
5
# decode a given string by removing duplicate occurrences | function to count the appearances of each character ; if the character is lower case ; if the character is uppercase ; if the character is a punctuation mark ; function to decode the given encoded string ; iterate the given string str ; find the index of the next character to be printed ; 
def findRepetition(a):
    if a <= 'z' and a >= 'a':
        return ord(a) - 97
    elif a <= 'Z' and a >= 'A':
        return ord(a) - 65
    else:
        return 0


def decodeString(str_):
    output = ""
    i = 0
    while (i < len(str_)):
        output += str_[i]
        i += findRepetition(str_[i]) + 1
    print("Decrypted code is {" + output + "}")


str_ = "abbbb acccdddd"
decodeString(str_)

# Expected output:
Decrypted code is {abb acd}
# program to perform a letter frequency attack on a monoalphabetic substitution cipher | function to decrypt a monoalphabetic substitution cipher using the letter frequency attack ; stores final 5 possible deciphered plaintext ; store the frequency of each letter in cipher text ; stores the frequency of each letter in cipher text in descending order ; store which alphabet is used already ; traverse the string s ; copy the frequency array ; stores the string formed from concatanating the english letters in the decreasing frequency in the english language ; sort the array in descending order ; itearate over the range [ 0 , 5 ] ; iterate over the range [ 0 , 26 ] ; store the numerical equivalent of letter at ith index of array letter_frequency ; calculate the probable shift used in monoalphabetic cipher ; temporary string to generate one plaintext at a time ; generate the probable ith plaintext string using the shift calculated above ; insert whitespaces as it is ; shift the kth letter of the cipher by x ; add the kth calculated / shifted letter to temporary string ; print the generated 5 possible plaintexts ; 
def printString(S, N):
    plaintext = [None] * 5
    freq = [0] * 26
    freqSorted = [None] * 26
    used = [0] * 26
    for i in range(N):
        if S[i] != ' ':
            freq[ord(S[i]) - 65] += 1
    for i in range(26):
        freqSorted[i] = freq[i]
    T = "ETAOINSHRDLCUMWFGYPBVKJXQZ"
    freqSorted .sort(reverse=True)
    for i in range(5):
        ch = -1
        for j in range(26):
            if freqSorted[i] == freq[j] and used[j] == 0:
                used[j] = 1
                ch = j
                break
        if ch == -1:
            break
        x = ord(T[i]) - 65
        x = x - ch
        curr = ""
        for k in range(N):
            if S[k] == ' ':
                curr += " "
                continue
            y = ord(S[k]) - 65
            y += x
            if y < 0:
                y += 26
            if y > 25:
                y -= 26
            curr += chr(y + 65)
        plaintext[i] = curr
    for i in range(5):
        print(plaintext[i])


S = "B TJNQMF NFTTBHF"
N = len(S)
printString(S, N)

# Expected output:
A SIMPLE MESSAGE
B TJNQMF NFTTBHF
A SIMPLE MESSAGE
C UKORNG OGUUCIG
C UKORNG OGUUCIG
# count of substrings in a binary string that contains more 1 s than 0 s | function to merge two partitions such that the merged array is sorted ; counting inversions ; function to implement merge sort ; function to calculate number of inversions in a given array ; calculate the number of inversions ; return the number of inversions ; function to count the number of substrings that contains more 1 s than 0 s ; stores the prefix sum array ; stores the count of valid substrings ; 
def merge(v, left, mid, right, inversions):
    temp = [0 for i in range(right - left + 1)]
    i = left
    j = mid + 1
    k = 0
    cnt = 0
    while (i <= mid and j <= right):
        if (v[i] <= v[j]):
            temp[k] = v[i]
            k += 1
            i += 1
        else:
            inversions += (mid - i + 1)
            temp[k] = v[j]
            k += 1
            j += 1
    while (i <= mid):
        temp[k] = v[i]
        k += 1
        i += 1
    while (j <= right):
        temp[k] = v[j]
        k += 1
        j += 1
    k = 0
    for a in range(left, right + 1, 1):
        v[a] = temp[k]
        k += 1


def mergeSort(v, left, right, inversions):
    if (left < right):
        mid = (left + right) // 2
        mergeSort(v, left, mid, inversions)
        mergeSort(v, mid + 1, right, inversions)
        merge(v, left, mid, right, inversions)


def CountInversions(v):
    n = len(v)
    inversions = 0
    mergeSort(v, 0, n - 1, inversions)
    return inversions


def getSubsCount(input):
    n = len(input)
    nums = [0 for i in range(n)]
    for i in range(n):
        nums[i] = ord(input[i]) - 48
        if (nums[i] == 0):
            nums[i] = -1
    pref = [0 for i in range(n)]
    sum = 0
    for i in range(n):
        sum += nums[i]
        pref[i] = sum
    cnt = 0
    for i in range(n):
        if (pref[i] > 0):
            cnt += 1
    pref = pref[:-1]
    inversions = CountInversions(pref)
    ans = cnt + inversions + 1
    return ans


if __name__ == '__main__':
    input = "101"
    ans = getSubsCount(input)
    print(ans)

# Expected output:
3
# check if a string consisting only of a , b , c can be made empty by removing substring " abc " recursively | function to check if the given string s can be made empty ; stores the characters of the string s ; traverse the given string ; if the character is c ; if stack size is greater than 2 ; pop from the stack ; top two characters in the stack should be ' b ' and ' a ' respectively ; otherwise , print no ; if character is ' a ' or ' b ' push to stack ; if stack is empty , then print yes . otherwise print no ; 
def canMadeEmpty(s, n):
    st = []
    for i in range(n):
        if s[i] == 'c':
            if len(st) >= 2:
                b = st[-1]
                st .pop()
                a = st[-1]
                st .pop()
                if a != 'a' or b != 'b':
                    return "No"
            else:
                return "No"
        else:
            st .append(s[i])
    if len(st) == 0:
        return "Yes"
    else:
        return "No"


s = "aabcbc"
n = len(s)
print(canMadeEmpty(s, n))

# Expected output:
Yes
# check if summation of two words is equal to target word | function to check weather summation of two words equal to target word ; store the length of each string ; reverse the strings a , b and c ; stores the remainder ; iterate in the range [ 0 , max ( l , max ( m , n ) ) ] ; stores the integer at ith position from the right in the sum of a and b ; if i is less than l ; if i is less than m ; update rem and curr ; if i is less than n and curr is not equal to c [ i ] - ' a ' , return " no " ; if rem is greater than 0 , return " no " ; otherwise , return " yes " ; 
def isSumEqual(A, B, C):
    L = len(A)
    M = len(B)
    N = len(A)
    A = A[::-1]
    B = B[::-1]
    C = C[::-1]
    rem = 0
    for i in range(max(L, max(M, N))):
        curr = rem
        if (i < L):
            curr += ord(A[i]) - ord('a')
        if (i < M):
            curr += ord(B[i]) - ord('a')
        rem = curr // 10
        curr %= 10
        if (i < N and curr != ord(C[i]) - ord('a')):
            return "No"
    if (rem):
        return "No"
    else:
        return "Yes"


if __name__ == '__main__':
    A = "acb"
    B = "cba"
    C = "cdb"
    print(isSumEqual(A, B, C))

# Expected output:
Yes
# minimum k such that every substring of length at least k contains a character c | set | function to find minimum value of k such that there exist atleast one k amazing character ; stores the answer ; update the s ; iterate over the characters in range [ a , z ] ; stores the last index where c appears ; stores the maximum possible length ; update s ; iterate over characters of string s ; if s [ i ] is equal to c ; stores the distance between positions of two same c ; update max_len ; update the value of prev ; update the value of ans ; return the answer ; 
def MinimumLengthSubstring(S, N):
    ans = N
    S = "0" + S + "0"
    S = [i for i in S]
    for c in range(ord('a'), ord('z') + 1):
        prev = 0
        max_len = 0
        S[0] = chr(c)
        S[N + 1] = chr(c)
        for i in range(1, N + 2):
            if (S[i] == chr(c)):
                len = i - prev
                max_len = max(max_len, len)
                prev = i
        ans = min(ans, max_len)
    return ans


if __name__ == '__main__':
    S = "abcde"
    N = len(S)
    print(MinimumLengthSubstring(S, N))

# Expected output:
3
# minimize hamming distance in binary string by setting only one k size substring bits | function to find minimum hamming distance after atmost one operation ; store the size of the string ; store the prefix sum of 1 s ; create prefix sum array ; initialize cnt as number of ones in string s ; store the required result ; traverse the string , s ; store the number of 1 s in the substring s [ i , i + k - 1 ] ; update the answer ; return the result ; 
def minimumHammingDistance(S, K):
    n = len(S)
    pref = [0] * n
    pref[0] = ord(S[0]) - ord('0')
    for i in range(1, n):
        pref[i] = pref[i - 1] + (ord(S[i]) - ord('0'))
    cnt = pref[n - 1]
    ans = cnt
    for i in range(n - K):
        value = pref[i + K - 1] - (pref[i - 1]if (i - 1) >= 0 else 0)
        ans = min(ans, cnt - value + (K - value))
    return ans


if __name__ == '__main__':
    s = "101"
    K = 2
    print(minimumHammingDistance(s, K))

# Expected output:
2
# check if a permutation of s2 can be obtained by adding or removing characters from s1 | python 3 program for the above approach ; function to check if the given number is prime or not ; if the number is less than 2 ; if the number is 2 ; if n is a multiple of 2 ; otherwise , check for the odds values ; function to check if s1 can be a permutation of s2 by adding or removing characters from s1 ; initialize a frequency array ; decrement the frequency for occurrence in s1 ; increment the frequency for occurence in s2 ; if frequency of current char is same in s1 and s2 ; check the frequency for the current char is not prime ; print the result ; 

from math import sqrt


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


def checkPermutation(s1, s2):
    freq = [0 for i in range(26)]
    for ch in s1:
        if ord(ch) - 97 in freq:
            freq[ord(ch) - 97] -= 1
        else:
            freq[ord(ch) - 97] = 1
    for ch in s2:
        if ord(ch) - 97 in freq:
            freq[ord(ch) - 97] += 1
        else:
            freq[ord(ch) - 97] = 1
    isAllChangesPrime = True
    for i in range(26):
        if (freq[i] == 0):
            continue
        elif (isPrime(abs(freq[i])) == False):
            isAllChangesPrime = False
            break
    if (isAllChangesPrime == False):
        print("Yes")
    else:
        print("No")


if __name__ == '__main__':
    S1 = "gekforgk"
    S2 = "geeksforgeeks"
    checkPermutation(S1, S2)

# Expected output:
Yes
# check if string formed by first and last x characters of a string is a palindrome | function to check whether the first x characters of both string str and reversed string str are same or not ; length of the string str ; traverse over the string while first and last x characters are not equal ; if the current and n - k - 1 from last character are not equal ; finally , print true ; 
def isEqualSubstring(string, x):
    n = len(string)
    i = 0
    while i < n and i < x:
        if (string[i] != string[n - i - 1]):
            print("false")
            return
        i += 1
    print("true")
    return


if __name__ == '__main__':
    string = "GeeksforGeeks"
    x = 3
    isEqualSubstring(string, x)

# Expected output:
false
# flip the string by either swapping given characters or rotating it horizontally for q queries | function to find final string after applying all queries on it ; traverse the queries array ; convert a , b to zero indexing ; query of 1 st type ; swap ath and bth characters ; query of 2 nd type ; swap first n characters with last n characters ; print answer ; 
def solve(S, N, Queries, Q):
    S = list(S)
    for i in range(Q):
        T = Queries[i][0]
        A = Queries[i][1]
        B = Queries[i][2]
        A -= 1
        B -= 1
        if (T == 1):
            temp = S[A]
            S[A] = S[B]
            S[B] = temp
        else:
            for j in range(N):
                temp = S[j]
                S[j] = S[j + N]
                S[j + N] = temp
    S = ''.join(S)
    print(S)


if __name__ == '__main__':
    S = "ABCD"
    N = len(S) // 2
    Queries = [[2, 0, 0], [1, 1, 3], [2, 0, 0]]
    Q = len(Queries)
    solve(S, N, Queries, Q)

# Expected output:
CBAD
# minimum number of replacement done of substring "01" with "110" to remove it completely | function to find the minimum number of replacement of "01" with "110" s . t . s doesn 't contain substring "10" ; stores the number of operations performed ; stores the resultant count of substrings ; traverse the string s from end ; if the current character is 0 ; if the current character is 1 ; print the result ; 
def minimumOperations(S, N):
    ans = 0
    cntOne = 0
    i = N - 1
    while (i >= 0):
        if (S[i] == '0'):
            ans += cntOne
            cntOne *= 2
        else:
            cntOne += 1
        i -= 1
    print(ans)


if __name__ == '__main__':
    S = "001"
    N = len(S)
    minimumOperations(S, N)

# Expected output:
3
# count different bitwise or values of equal length strings s1 and s2 by swapping exactly one pair of characters from the first string | function to find the number of ways to obtain different bitwise or ; stores the count of pairs t00 , t10 , t01 , t11 ; traverse the characters of the string s1 and s2 ; count the pair ( 0 , 0 ) ; count the pair ( 1 , 0 ) ; count the pair ( 1 , 1 ) ; count the pair ( 0 , 1 ) ; number of ways to calculate the different bitwise or ; print the result ; 
def differentBitwiseOR(s1, s2):
    n = len(s1)
    t00 = 0
    t10 = 0
    t01 = 0
    t11 = 0
    for i in range(n):
        if (s1[i] == '0' and s2[i] == '0'):
            t00 += 1
        if (s1[i] == '1' and s2[i] == '0'):
            t10 += 1
        if (s1[i] == '1' and s2[i] == '1'):
            t11 += 1
        if (s1[i] == '0' and s2[i] == '1'):
            t01 += 1
    ans = t00 * t10 + t01 * t10 + t00 * t11
    print(ans)


S1 = "01001"
S2 = "11011"
differentBitwiseOR(S1, S2)

# Expected output:
2
# flip all 0 s in given binary strings k times with different neighbours | function to modify the given string k number of times by flipping 0 s having different adjacent characters ; size of the string ; stores modified string after each iteration ; iterate over the range [ 0 k ] ; traverse the string s ; if '0' is present at 0 th index then replace it with 1 st index ; if '0' is present at the last index then replace it with last index - 1 character ; otherwise , convert 0 s to 1 if the adjacent characters are different ; if during this iteration there is no change in the string then break this loop ; update the string s ; print the updated string ; 
def convertString(S, k):
    n = len(S)
    temp = S
    temp = list(temp)
    for i in range(k):
        for j in range(n - 1):
            if (j == 0 and S[j] == '0'):
                temp[j] = S[j + 1]
            elif (j == n - 1 and S[j] == '0'):
                temp[j] = S[j - 1]
            elif (S[j - 1] != S[j + 1] and S[j] == '0'):
                temp[j] = '1'
        if (S == temp):
            break
        temp = ''.join(temp)
        S = temp
    print(S)


if __name__ == '__main__':
    S = "10010001"
    K = 1
    convertString(S, K)

# Expected output:
11111011