giulio98/xlcost-single-prompt huggingface dataset:
# count of n digit numbers whose sum of digits equals to given sum | a lookup table used for memoization ; memoization based implementation of recursive function ; base case ; if this subproblem is already evaluated , return the evaluated value ; initialize answer ; traverse through every digit and recursively count numbers beginning with it ; this is mainly a wrapper over countrec . it explicitly handles leading digit and calls countrec ( ) for remaining n . ; initialize final answer ; traverse through every digit from 1 to 9 and count numbers beginning with it ; 

lookup = [[-1 for i in range(501)]for i in range(101)]


def countRec(n, Sum):
    if (n == 0):
        return Sum == 0
    if (lookup[n][Sum] != -1):
        return lookup[n][Sum]
    ans = 0
    for i in range(10):
        if (Sum - i >= 0):
            ans += countRec(n - 1, Sum - i)
    lookup[n][Sum] = ans
    return lookup[n][Sum]


def finalCount(n, Sum):
    ans = 0
    for i in range(1, 10):
        if (Sum - i >= 0):
            ans += countRec(n - 1, Sum - i)
    return ans


n, Sum = 3, 5
print(finalCount(n, Sum))

# Expected output:
15
# count of n digit numbers whose sum of digits equals to given sum | python3 program to count of n digit numbers whose sum of digits equals to given sum ; in case n = 2 start is 10 and end is ( 100 - 1 ) = 99 ; 

import math


def findCount(n, sum):
    start = math .pow(10, n - 1)
    end = math .pow(10, n) - 1
    count = 0
    i = start
    while (i <= end):
        cur = 0
        temp = i
        while (temp != 0):
            cur += temp % 10
            temp = temp // 10
        if (cur == sum):
            count = count + 1
            i += 9
        else:
            i = i + 1
    print(count)


n = 3
sum = 5
findCount(n, sum)

# Expected output:
15
# total number of non | python3 program to count non - decreasing number with n digits ; dp [ i ] [ j ] contains total count of non decreasing numbers ending with digit i and of length j ; fill table for non decreasing numbers of length 1. base cases 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ; fill the table in bottom - up manner ; compute total numbers of non decreasing numbers of length 'len   ; sum of all numbers of length of len - 1 in which last digit x is <= 'digit   ; there total nondecreasing numbers of length n won 't be dp[0][n] +  dp[1][n] ..+ dp[9][n] ; 
def countNonDecreasing(n):
    dp = [[0 for i in range(n + 1)]for i in range(10)]
    for i in range(10):
        dp[i][1] = 1
    for digit in range(10):
        for len in range(2, n + 1):
            for x in range(digit + 1):
                dp[digit][len] += dp[x][len - 1]
    count = 0
    for i in range(10):
        count += dp[i][n]
    return count


n = 3
print(countNonDecreasing(n))

# Expected output:
220
# total number of non | python program to count non - decreasing numner with n digits ; compute value of n * ( n + 1 ) / 2 * ( n + 2 ) / 3 * ... . * ( n + n - 1 ) / n ; 
def countNonDecreasing(n):
    N = 10
    count = 1
    for i in range(1, n + 1):
        count = int(count * (N + i - 1))
        count = int(count / i)
    return count


n = 3
print(countNonDecreasing(n))

# Expected output:
220
# minimum number of squares whose sum equals to given number n | returns count of minimum squares that sum to n ; base cases ; getminsquares rest of the table using recursive formula maximum squares required is n ( 1 * 1 + 1 * 1 + . . ) ; go through all smaller numbers to recursively find minimum ; 
def getMinSquares(n):
    if n <= 3:
        return n
    res = n
    for x in range(1, n + 1):
        temp = x * x
        if temp > n:
            break
        else:
            res = min(res, 1 + getMinSquares(n - temp))
    return res


print(getMinSquares(6))

# Expected output:
3
# minimum number of squares whose sum equals to given number n | a dynamic programming based python program to find minimum number of squares whose sum is equal to a given number ; returns count of minimum squares that sum to n ; getminsquares table for base case entries ; getminsquares rest of the table using recursive formula ; max value is i as i can always be represented as 1 * 1 + 1 * 1 + ... ; go through all smaller numbers to recursively find minimum ; store result ; 

from math import ceil, sqrt


def getMinSquares(n):
    dp = [0, 1, 2, 3]
    for i in range(4, n + 1):
        dp .append(i)
        for x in range(1, int(ceil(sqrt(i))) + 1):
            temp = x * x
            if temp > i:
                break
            else:
                dp[i] = min(dp[i], 1 + dp[i - temp])
    return dp[n]


print(getMinSquares(6))

# Expected output:
3
# minimum number of squares whose sum equals to given number n | python3 program for the above approach ; function to count minimum squares that sum to n ; creating visited vector of size n + 1 ; queue of pair to store node and number of steps ; initially ans variable is initialized with inf ; push starting node with 0 0 indicate current number of step to reach n ; mark starting node visited ; if node reaches its destination 0 update it with answer ; loop for all possible path from 1 to i * i <= current node ( p . first ) ; if we are standing at some node then next node it can jump to will be current node - ( some square less than or equal n ) ; check if it is valid and not visited yet ; mark visited ; push it it queue ; return ans to calling function ; 

import sys


def numSquares(n):
    visited = [0] * (n + 1)
    q = []
    ans = sys .maxsize
    q .append([n, 0])
    visited[n] = 1
    while (len(q) > 0):
        p = q[0]
        q .pop(0)
        if (p[0] == 0):
            ans = min(ans, p[1])
        i = 1
        while i * i <= p[0]:
            path = p[0] - i * i
            if path >= 0 and (visited[path] == 0 or path == 0):
                visited[path] = 1
                q .append([path, p[1] + 1])
            i += 1
    return ans


print(numSquares(12))

# Expected output:
3
# find minimum number of coins that make a given value | a naive recursive python program to find minimum of coins to make a given change v ; m is size of coins array ( number of different coins ) ; base case ; initialize result ; try every coin that has smaller value than v ; check for int_max to avoid overflow and see if result can minimized ; 

import sys


def minCoins(coins, m, V):
    if (V == 0):
        return 0
    res = sys .maxsize
    for i in range(0, m):
        if (coins[i] <= V):
            sub_res = minCoins(coins, m, V - coins[i])
            if (sub_res != sys .maxsize and sub_res + 1 < res):
                res = sub_res + 1
    return res


coins = [9, 6, 5, 1]
m = len(coins)
V = 11
print("Minimum coins required is", minCoins(coins, m, V))

# Expected output:
Minimum coins required is 2
# find minimum number of coins that make a given value | a dynamic programming based python3 program to find minimum of coins to make a given change v ; m is size of coins array ( number ofdifferent coins ) ; table [ i ] will be storing the minimum number of coins required for i value . so table [ v ] will have result ; base case ( if given value v is 0 ) ; initialize all table values as infinite ; compute minimum coins required for all values from 1 to v ; go through all coins smaller than i ; 

import sys


def minCoins(coins, m, V):
    table = [0 for i in range(V + 1)]
    table[0] = 0
    for i in range(1, V + 1):
        table[i] = sys .maxsize
    for i in range(1, V + 1):
        for j in range(m):
            if (coins[j] <= i):
                sub_res = table[i - coins[j]]
                if (sub_res != sys .maxsize and sub_res + 1 < table[i]):
                    table[i] = sub_res + 1
    if table[V] == sys .maxsize:
        return -1
    return table[V]


if __name__ == "__main__":
    coins = [9, 6, 5, 1]
    m = len(coins)
    V = 11
    print("Minimum coins required is ", minCoins(coins, m, V))

# Expected output:
Minimum coins required is  2
# shortest common supersequence | a naive recursive python program to find length of the shortest supersequence ; 
def superSeq(X, Y, m, n):
    if (not m):
        return n
    if (not n):
        return m
    if (X[m - 1] == Y[n - 1]):
        return 1 + superSeq(X, Y, m - 1, n - 1)
    return 1 + min(superSeq(X, Y, m - 1, n), superSeq(X, Y, m, n - 1))


X = "AGGTAB"
Y = "GXTXAYB"
print(
    "Length of the shortest supersequence is %d" %
    superSeq(
        X,
        Y,
        len(X),
        len(Y)))

# Expected output:
Length of the shortest supersequence is 9
# shortest common supersequence | returns length of the shortest supersequence of x and y ; fill table in bottom up manner ; below steps follow above recurrence ; 
def superSeq(X, Y, m, n):
    dp = [[0] * (n + 2)for i in range(m + 2)]
    for i in range(m + 1):
        for j in range(n + 1):
            if (not i):
                dp[i][j] = j
            elif (not j):
                dp[i][j] = i
            elif (X[i - 1] == Y[j - 1]):
                dp[i][j] = 1 + dp[i - 1][j - 1]
            else:
                dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1])
    return dp[m][n]


X = "AGGTAB"
Y = "GXTXAYB"
print(
    "Length of the shortest supersequence is %d" %
    superSeq(
        X,
        Y,
        len(X),
        len(Y)))

# Expected output:
Length of the shortest supersequence is 9
# compute sum of digits in all numbers from 1 to n | returns sum of all digits in numbers from 1 to n ; initialize result ; one by one compute sum of digits in every number from 1 to n ; a utility function to compute sum of digits in a given number x ; 
def sumOfDigits(x):
    sum = 0
    while (x != 0):
        sum = sum + x % 10
        x = x // 10
    return sum


def sumOfDigitsFrom1ToN(n):
    result = 0
    for x in range(1, n + 1):
        result = result + sumOfDigits(x)
    return result


n = 328
print("Sum of digits in numbers from 1 to", n, "is", sumOfDigitsFrom1ToN(n))

# Expected output:
Sum of digits in numbers from 1 to 328 is 3241
# compute sum of digits in all numbers from 1 to n | python 3 program to compute sum of digits in numbers from 1 to n ; function to computer sum of digits in numbers from 1 to n . comments use example of 328 to explain the code ; base case : if n < 10 return sum of first n natural numbers ; d = number of digits minus one in n . for 328 , d is 2 ; computing sum of digits from 1 to 10 ^ d - 1 , d = 1 a [ 0 ] = 0 ; d = 2 a [ 1 ] = sum of digit from 1 to 9 = 45 d = 3 a [ 2 ] = sum of digit from 1 to 99 = a [ 1 ] * 10 + 45 * 10 ^ 1 = 900 d = 4 a [ 3 ] = sum of digit from 1 to 999 = a [ 2 ] * 10 + 45 * 10 ^ 2 = 13500 ; computing 10 ^ d ; most significant digit ( msd ) of n , for 328 , msd is 3 which can be obtained using 328 / 100 ; explanation for first and second terms in below line of code first two terms compute sum of digits from 1 to 299 ( sum of digits in range 1 - 99 stored in a [ d ] ) + ( sum of digits in range 100 - 199 , can be calculated as 1 * 100 + a [ d ] . ( sum of digits in range 200 - 299 , can be calculated as 2 * 100 + a [ d ] the above sum can be written as 3 * a [ d ] + ( 1 + 2 ) * 100 explanation for third and fourth terms in below line of code the last two terms compute sum of digits in number from 300 to 328. the third term adds 3 * 29 to sum as digit 3 occurs in all numbers from 300 to 328. the fourth term recursively calls for 28 ; 

import math


def sumOfDigitsFrom1ToN(n):
    if (n < 10):
        return (n * (n + 1) / 2)
    d = (int)(math .log10(n))
    a = [0] * (d + 1)
    a[0] = 0
    a[1] = 45
    for i in range(2, d + 1):
        a[i] = a[i - 1] * 10 + 45 * (int)(math .ceil(math .pow(10, i - 1)))
    p = (int)(math .ceil(math .pow(10, d)))
    msd = n // p
    return (int)(msd * a[d] + (msd * (msd - 1) // 2) *
                 p + msd * (1 + n % p) + sumOfDigitsFrom1ToN(n % p))


n = 328
print("Sum of digits in numbers from 1 to", n, "is", sumOfDigitsFrom1ToN(n))

# Expected output:
Sum of digits in numbers from 1 to 328 is 3241
# compute sum of digits in all numbers from 1 to n | python program to compute sum of digits in numbers from 1 to n ; function to computer sum of digits in numbers from 1 to n ; 

import math


def sumOfDigitsFrom1ToNUtil(n, a):
    if (n < 10):
        return (n * (n + 1)) // 2
    d = int(math .log(n, 10))
    p = int(math .ceil(pow(10, d)))
    msd = n // p
    return (msd * a[d] + (msd * (msd - 1) // 2) * p + msd *
            (1 + n % p) + sumOfDigitsFrom1ToNUtil(n % p, a))


def sumOfDigitsFrom1ToN(n):
    d = int(math .log(n, 10))
    a = [0] * (d + 1)
    a[0] = 0
    a[1] = 45
    for i in range(2, d + 1):
        a[i] = a[i - 1] * 10 + 45 * int(math .ceil(pow(10, i - 1)))
    return sumOfDigitsFrom1ToNUtil(n, a)


n = 328
print("Sum of digits in numbers from 1 to", n, "is", sumOfDigitsFrom1ToN(n))

# Expected output:
Sum of digits in numbers from 1 to 328 is 3241
# count possible ways to construct buildings | returns count of possible ways for n sections ; base case ; 2 for one side and 4 for two sides ; countb is count of ways with a building at the end counts is count of ways with a space at the end prev_countb and prev_counts are previous values of countb and counts respectively . initialize countb and counts for one side ; use the above recursive formula for calculating countb and counts using previous values ; result for one side is sum of ways ending with building and ending with space ; result for 2 sides is square of result for one side ; 
def countWays(N):
    if (N == 1):
        return 4
    countB = 1
    countS = 1
    for i in range(2, N + 1):
        prev_countB = countB
        prev_countS = countS
        countS = prev_countB + prev_countS
        countB = prev_countS
    result = countS + countB
    return (result * result)


if __name__ == "__main__":
    N = 3
    print("Count of ways for ", N, " sections is ", countWays(N))

# Expected output:
Count of ways for  3  sections is  25
# count number of ways to reach a given score in a game | returns number of ways to reach score n . ; table [ i ] will store count of solutions for value i . initialize all table values as 0. ; base case ( if given value is 0 ) ; one by one consider given 3 moves and update the table [ ] values after the index greater than or equal to the value of the picked move . ; 
def count(n):
    table = [0 for i in range(n + 1)]
    table[0] = 1
    for i in range(3, n + 1):
        table[i] += table[i - 3]
    for i in range(5, n + 1):
        table[i] += table[i - 5]
    for i in range(10, n + 1):
        table[i] += table[i - 10]
    return table[n]


n = 20
print('Count for', n, 'is', count(n))
n = 13
print('Count for', n, 'is', count(n))

# Expected output:
Count for 20 is 4
Count for 13 is 2
# naive algorithm for pattern searching | python3 program for naive pattern searching algorithm ; 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 ] ; 
def search(pat, txt):
    M = len(pat)
    N = len(txt)
    for i in range(N - M + 1):
        j = 0
        while (j < M):
            if (txt[i + j] != pat[j]):
                break
            j += 1
        if (j == M):
            print("Pattern found at index ", i)


if __name__ == '__main__':
    txt = "AABAACAADAABAAABAA"
    pat = "AABA"
    search(pat, txt)

# Expected output:
Pattern found at index  0
Pattern found at index  9
Pattern found at index  13
# rabin | d is the number of characters in the input alphabet ; pat -> pattern txt -> text q -> a prime number ; hash value for pattern ; hash value for txt ; the value of h would be " pow ( d , ▁ m - 1 ) % q " ; calculate the hash value of pattern and first window of text ; slide the pattern over text one by one ; check the hash values of current window of text and pattern if the hash values match then only check for characters on by one ; check for characters one by one ; if p == t and pat [ 0. . . m - 1 ] = txt [ i , i + 1 , ... i + m - 1 ] ; calculate hash value for next window of text : remove leading digit , add trailing digit ; we might get negative values of t , converting it to positive ; 

d = 256


def search(pat, txt, q):
    M = len(pat)
    N = len(txt)
    i = 0
    j = 0
    p = 0
    t = 0
    h = 1
    for i in range(M - 1):
        h = (h * d) % q
    for i in range(M):
        p = (d * p + ord(pat[i])) % q
        t = (d * t + ord(txt[i])) % q
    for i in range(N - M + 1):
        if p == t:
            for j in range(M):
                if txt[i + j] != pat[j]:
                    break
                else:
                    j += 1
            if j == M:
                print("Pattern found at index " + str(i))
        if i < N - M:
            t = (d * (t - ord(txt[i]) * h) + ord(txt[i + M])) % q
            if t < 0:
                t = t + q


txt = "GEEKS FOR GEEKS"
pat = "GEEK"
q = 101
search(pat, txt, q)

# Expected output:
Pattern found at index 0
Pattern found at index 10
# optimized naive algorithm for pattern searching | python program for a modified naive pattern searching algorithm that is optimized for the cases when all characters of pattern are different ; for current index i , check for pattern match ; if pat [ 0. . . m - 1 ] = txt [ i , i + 1 , ... i + m - 1 ] ; slide the pattern by j ; 
def search(pat, txt):
    M = len(pat)
    N = len(txt)
    i = 0
    while i <= N - M:
        for j in range(M):
            if txt[i + j] != pat[j]:
                break
            j += 1
        if j == M:
            print("Pattern found at index " + str(i))
            i = i + M
        elif j == 0:
            i = i + 1
        else:
            i = i + j


txt = "ABCEABCDABCEABCD"
pat = "ABCD"
search(pat, txt)

# Expected output:
Pattern found at index 4
Pattern found at index 12
# boyer moore algorithm for pattern searching | python3 program for bad character heuristic of boyer moore string matching algorithm ; the preprocessing function for boyer moore 's bad character heuristic   ; initialize all occurrence as - 1 ; fill the actual value of last occurrence ; a pattern searching function that uses bad character heuristic of boyer moore algorithm ; create the bad character list by calling the preprocessing function badcharheuristic ( ) for given pattern ; s is shift of the pattern with respect to text ; there are n - m + 1 potential allignments ; keep reducing index j of pattern while characters of pattern and text are matching at this shift s ; if the pattern is present at current shift , then index j will become - 1 after the above loop ; shift the pattern so that the next character in text aligns with the last occurrence of it in pattern . the condition s + m < n is necessary for the case when pattern occurs at the end of text ; shift the pattern so that the bad character in text aligns with the last occurrence of it in pattern . the max function is used to make sure that we get a positive shift . we may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character . ; 

NO_OF_CHARS = 256


def badCharHeuristic(string, size):
    badChar = [-1] * NO_OF_CHARS
    for i in range(size):
        badChar[ord(string[i])] = i
    return badChar


def search(txt, pat):
    m = len(pat)
    n = len(txt)
    badChar = badCharHeuristic(pat, m)
    s = 0
    while (s <= n - m):
        j = m - 1
        while j >= 0 and pat[j] == txt[s + j]:
            j -= 1
        if j < 0:
            print("Pattern occur at shift = {}".format(s))
            s += (m - badChar[ord(txt[s + m])]if s + m < n else 1)
        else:
            s += max(1, j - badChar[ord(txt[s + j])])


def main():
    txt = "ABAAABCD"
    pat = "ABC"
    search(txt, pat)


if __name__ == '__main__':
    main()

# Expected output:
Pattern occur at shift = 4
# anagram substring search ( or search for all permutations ) | python program to search all anagrams of a pattern in a text ; this function returns true if contents of arr1 [ ] and arr2 [ ] are same , otherwise false . ; this function search for all permutations of pat [ ] in 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 [ ] ; add current character to current window ; remove the first character of previous window ; check for the last window in text ; 

MAX = 256


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


def search(pat, txt):
    M = len(pat)
    N = len(txt)
    countP = [0] * MAX
    countTW = [0] * MAX
    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):
            print("Found at Index", (i - M))
        (countTW[ord(txt[i])]) += 1
        (countTW[ord(txt[i - M])]) -= 1
    if compare(countP, countTW):
        print("Found at Index", N - M)


txt = "BACDGABCDA"
pat = "ABCD"
search(pat, txt)

# Expected output:
Found at Index 0
Found at Index 5
Found at Index 6
# median of two sorted arrays of same size | this function returns median of ar1 [ ] and ar2 [ ] . assumptions in this function : both ar1 [ ] and ar2 [ ] are sorted arrays both have n elements ; since there are 2 n elements , median will be average of elements at index n - 1 and n in the array obtained after merging ar1 and ar2 ; below is to handle case where all elements of ar1 [ ] are smaller than smallest ( or first ) element of ar2 [ ] ; below is to handle case where all elements of ar2 [ ] are smaller than smallest ( or first ) element of ar1 [ ] ; equals sign because if two arrays have some common elements ; store the prev median ; store the prev median ; 
def getMedian(ar1, ar2, n):
    i = 0
    j = 0
    m1 = -1
    m2 = -1
    count = 0
    while count < n + 1:
        count += 1
        if i == n:
            m1 = m2
            m2 = ar2[0]
            break
        elif j == n:
            m1 = m2
            m2 = ar1[0]
            break
        if ar1[i] <= ar2[j]:
            m1 = m2
            m2 = ar1[i]
            i += 1
        else:
            m1 = m2
            m2 = ar2[j]
            j += 1
    return (m1 + m2) / 2


ar1 = [1, 12, 15, 26, 38]
ar2 = [2, 13, 17, 30, 45]
n1 = len(ar1)
n2 = len(ar2)
if n1 == n2:
    print("Median is ", getMedian(ar1, ar2, n1))
else:
    print("Doesn't work for arrays of unequal size")

# Expected output:
Median is  16.0
# median of two sorted arrays of same size | while loop to swap all smaller numbers to arr1 ; 
def getMedian(ar1, ar2, n):
    i, j = n - 1, 0
    while (ar1[i] > ar2[j] and i > -1 and j < n):
        ar1[i], ar2[j] = ar2[j], ar1[i]
        i -= 1
        j += 1
    ar1 .sort()
    ar2 .sort()
    return (ar1[-1] + ar2[0]) >> 1


if __name__ == '__main__':
    ar1 = [1, 12, 15, 26, 38]
    ar2 = [2, 13, 17, 30, 45]
    n1, n2 = len(ar1), len(ar2)
    if (n1 == n2):
        print('Median is', getMedian(ar1, ar2, n1))
    else:
        print("Doesn't work for arrays of unequal size")

# Expected output:
Median is 16