giulio98/xlcost-single-prompt huggingface dataset:
# ways to fill n positions using m colors such that there are exactly k pairs of adjacent different colors | python 3 implementation of the approach ; recursive function to find the required number of ways ; when all positions are filled ; if adjacent pairs are exactly k ; if already calculated ; next position filled with same color ; next position filled with different color so there can be m - 1 different colors ; 

max = 4


def countWays(index, cnt, dp, n, m, k):
    if (index == n):
        if (cnt == k):
            return 1
        else:
            return 0
    if (dp[index][cnt] != -1):
        return dp[index][cnt]
    ans = 0
    ans += countWays(index + 1, cnt, dp, n, m, k)
    ans += (m - 1) * countWays(index + 1, cnt + 1, dp, n, m, k)
    dp[index][cnt] = ans
    return dp[index][cnt]


if __name__ == "__main__":
    n = 3
    m = 3
    k = 2
    dp = [[-1 for x in range(n + 1)]for y in range(max)]
    print(m * countWays(1, 0, dp, n, m, k))

# Expected output:
12
# number of balanced bracket expressions that can be formed from a string | max string length ; function to check whether index start and end can form a bracket pair or not ; check for brackets ( ) ; check for brackets [ ] ; check for brackets { } ; function to find number of proper bracket expressions ; if starting index is greater than ending index ; if dp [ start ] [ end ] has already been computed ; search for the bracket in from next index ; if bracket pair is formed , add number of combination ; if ? comes then all three bracket expressions are possible ; return answer ; if n is odd , string cannot be balanced ; 

MAX = 300


def checkFunc(i, j, st):
    if (st[i] == '(' and st[j] == ')'):
        return 1
    if (st[i] == '(' and st[j] == '?'):
        return 1
    if (st[i] == '?' and st[j] == ')'):
        return 1
    if (st[i] == '[' and st[j] == ']'):
        return 1
    if (st[i] == '[' and st[j] == '?'):
        return 1
    if (st[i] == '?' and st[j] == ']'):
        return 1
    if (st[i] == '{' and st[j] == '}'):
        return 1
    if (st[i] == '{' and st[j] == '?'):
        return 1
    if (st[i] == '?' and st[j] == '}'):
        return 1
    return 0


def countRec(start, end, dp, st):
    sum = 0
    if (start > end):
        return 1
    if (dp[start][end] != -1):
        return dp[start][end]
    r = 0
    for i in range(start + 1, end + 1, 2):
        if (checkFunc(start, i, st)):
            sum = (
                sum +
                countRec(
                    start +
                    1,
                    i -
                    1,
                    dp,
                    st) *
                countRec(
                    i +
                    1,
                    end,
                    dp,
                    st))
        elif (st[start] == '?' and st[i] == '?'):
            sum = (
                sum +
                countRec(
                    start +
                    1,
                    i -
                    1,
                    dp,
                    st) *
                countRec(
                    i +
                    1,
                    end,
                    dp,
                    st) *
                3)
    dp[start][end] = sum
    return dp[start][end]


def countWays(st):
    n = len(st)
    if (n % 2 == 1):
        return 0
    dp = [[-1 for i in range(MAX)]for i in range(MAX)]
    return countRec(0, n - 1, dp, st)


if __name__ == "__main__":
    st = "(?([?)]?}?"
    print(countWays(st))

# Expected output:
3
# sum of fibonacci numbers at even indexes upto n terms | computes value of first fibonacci numbers and stores the even - indexed sum ; initialize result ; add remaining terms ; for even indices ; return the alternting sum ; 
def calculateEvenSum(n):
    if n <= 0:
        return 0
    fibo = [0] * (2 * n + 1)
    fibo[0], fibo[1] = 0, 1
    sum = 0
    for i in range(2, 2 * n + 1):
        fibo[i] = fibo[i - 1] + fibo[i - 2]
        if i % 2 == 0:
            sum += fibo[i]
    return sum


if __name__ == "__main__":
    n = 8
    print("Even indexed Fibonacci Sum upto", n, "terms:", calculateEvenSum(n))

# Expected output:
Even indexed Fibonacci Sum upto 8 terms: 1596
# sum of fibonacci numbers at even indexes upto n terms | python3 program to find even indexed fibonacci sum in o ( log n ) time . ; create an array for memoization ; returns n 'th fibonacci number using table f[] ; base cases ; if fib ( n ) is already computed ; applying above formula [ note value n & 1 is 1 if n is odd , else 0 ] . ; computes value of even - indexed fibonacci sum ; 

MAX = 1000
f = [0] * MAX


def fib(n):
    if (n == 0):
        return 0
    if (n == 1 or n == 2):
        f[n] = 1
        return f[n]
    if (f[n]):
        return f[n]
    k = (n + 1) // 2 if (n % 2 == 1)else n // 2
    f[n] = (fib(k) * fib(k) + fib(k - 1) * fib(k - 1))if (n %
                                                          2 == 1)else (2 * fib(k - 1) + fib(k)) * fib(k)
    return f[n]


def calculateEvenSum(n):
    return (fib(2 * n + 1) - 1)


if __name__ == '__main__':
    n = 8
    print("Even indexed Fibonacci Sum upto", n, "terms:", calculateEvenSum(n))

# Expected output:
Even indexed Fibonacci Sum upto 8 terms: 1596
# count the number of ways to traverse a matrix | find factorial ; find number of ways to reach mat [ m - 1 ] [ n - 1 ] from mat [ 0 ] [ 0 ] in a matrix mat [ ] [ ] ] ; 
def factorial(n):
    res = 1
    for i in range(2, n + 1):
        res *= i
    return res


def countWays(m, n):
    m = m - 1
    n = n - 1
    return (factorial(m + n) // (factorial(m) * factorial(n)))


m = 5
n = 5
result = countWays(m, n)
print(result)

# Expected output:
70
# matrix chain multiplication ( a o ( n ^ 2 ) solution ) | matrix mi has dimension p [ i - 1 ] x p [ i ] for i = 1. . n ; for simplicity of the program , one extra row and one extra column are allocated in dp [ ] [ ] . 0 th row and 0 th column of dp [ ] [ ] are not used ; cost is zero when multiplying one matrix . ; simply following above recursive formula . ; 
def MatrixChainOrder(p, n):
    dp = [[0 for i in range(n)]for i in range(n)]
    for i in range(1, n):
        dp[i][i] = 0
    for L in range(1, n - 1):
        for i in range(n - L):
            dp[i][i + L] = min(dp[i + 1][i + L] + p[i - 1] * p[i] * p[i + L],
                               dp[i][i + L - 1] + p[i - 1] * p[i + L - 1] * p[i + L])
    return dp[1][n - 1]


arr = [10, 20, 30, 40, 30]
size = len(arr)
print("Minimum number of multiplications is", MatrixChainOrder(arr, size))

# Expected output:
Minimum number of multiplications is 30000
# count common subsequence in two strings | return the number of common subsequence in two strings ; for each character of s ; for each character in t ; if character are same in both the string ; 
def CommomSubsequencesCount(s, t):
    n1 = len(s)
    n2 = len(t)
    dp = [[0 for i in range(n2 + 1)]for i in range(n1 + 1)]
    for i in range(1, n1 + 1):
        for j in range(1, n2 + 1):
            if (s[i - 1] == t[j - 1]):
                dp[i][j] = (1 + dp[i][j - 1] + dp[i - 1][j])
            else:
                dp[i][j] = (dp[i][j - 1] + dp[i - 1][j] - dp[i - 1][j - 1])
    return dp[n1][n2]


s = "ajblqcpdz"
t = "aefcnbtdi"
print(CommomSubsequencesCount(s, t))

# Expected output:
11
# minimum number of palindromes required to express n as a sum | set 2 | a utility for creating palindrome ; checks if number of digits is odd or even if odd then neglect the last digit of _input in finding reverse as in case of odd number of digits middle element occur once ; creates palindrome by just appending reverse of number to itself ; function to generate palindromes ; run two times for odd and even length palindromes ; creates palindrome numbers with first half as i . value of j decides whether we need an odd length or even length palindrome . ; function to find the minimum number of palindromes required to express n as a sum ; checking if the number is a palindrome ; getting the list of all palindromes upto n ; sorting the list of palindromes ; the answer is three if the control reaches till this point ; 
def createPalindrome(_input, isOdd):
    n = palin = _input
    if isOdd:
        n //= 10
    while n > 0:
        palin = palin * 10 + (n % 10)
        n //= 10
    return palin


def generatePalindromes(N):
    palindromes = []
    for j in range(0, 2):
        i = 1
        number = createPalindrome(i, j)
        while number <= N:
            palindromes .append(number)
            i += 1
            number = createPalindrome(i, j)
    return palindromes


def minimumNoOfPalindromes(N):
    b = a = str(N)
    b = b[::-1]
    if a == b:
        return 1
    palindromes = sorted(generatePalindromes(N))
    l, r = 0, len(palindromes) - 1
    while l < r:
        if palindromes[l] + palindromes[r] == N:
            return 2
        elif palindromes[l] + palindromes[r] < N:
            l += 1
        else:
            r -= 1
    return 3


if __name__ == "__main__":
    N = 65
    print(minimumNoOfPalindromes(N))

# Expected output:
3
# sum of elements of all partitions of number such that no element is less than k | function that returns total number of valid partitions of integer n ; global declaration of 2d dp array which will be later used for memoization ; initializing 2d dp array with - 1 we will use this 2d array for memoization ; if this subproblem is already previously calculated , then directly return that answer ; if n < k , then no valid partition is possible ; if n is between k to 2 * k then there is only one partition and that is the number n itself ; initialize answer with 1 as the number n itself is always a valid partition ; for loop to iterate over k to n and find number of possible valid partitions recursively . ; memoization is done by storing this calculated answer ; returning number of valid partitions ; 
def countPartitions(n, k):
    dp = [[0] * 201] * 201
    for i in range(n + 1):
        for j in range(n + 1):
            dp[i][j] = -1
    if (dp[n][k] >= 0):
        return dp[n][k]
    if (n < k):
        return 0
    if (n < 2 * k):
        return 1
    answer = 1
    for i in range(k, n):
        answer = (answer + countPartitions(n - i, i))
    dp[n][k] = answer
    return answer


n = 10
k = 3
print(
    "Total Aggregate sum of all "
    "Valid Partitions: ",
    countPartitions(
        n,
        k) * n)

# Expected output:
Total Aggregate sum of all Valid Partitions:  50
# number of co | python3 program to count the pairs whose sum of digits is co - prime ; function to find the elements after doing the sum of digits ; traverse from a to b ; find the sum of the digits of the elements in the given range one by one ; function to count the co - prime pairs ; function to make the pairs by doing the sum of digits ; count pairs that are co - primes ; 

from math import gcd


def makePairs(pairs, a, b):
    for i in range(a, b + 1, 1):
        sumOfDigits = 0
        k = i
        while (k > 0):
            sumOfDigits += k % 10
            k = int(k / 10)
        if (sumOfDigits <= 162):
            pairs .append(sumOfDigits)


def countCoPrime(a, b):
    pairs = []
    makePairs(pairs, a, b)
    count = 0
    for i in range(0, len(pairs), 1):
        for j in range(i + 1, len(pairs), 1):
            if (gcd(pairs[i], pairs[j]) == 1):
                count += 1
    return count


if __name__ == '__main__':
    a = 12
    b = 15
    print(countCoPrime(a, b))

# Expected output:
4
# number of co | python3 program to count the pairs whose sum of digits is co - prime ; recursive function to return the frequency of numbers having their sum of digits i ; returns 1 or 0 ; returns value of the dp if already stored ; loop from digit 0 to 9 ; to change the tight to 1 ; calling the recursive function to find the frequency ; function to find out frequency of numbers from 1 to n having their sum of digits from 1 to 162 and store them in array ; number to string conversion ; calling the recursive function and pushing it into array ; function to find the pairs ; calling the formarray function of a - 1 numbers ; calling the formarray function of b numbers ; subtracting the frequency of higher number array with lower number array and thus finding the range of numbers from a to b having sum from 1 to 162 ; to find out total number of pairs which are co - prime ; 

import math


def recursive(idx, sum, tight, st, dp, num):
    if (idx == num):
        return sum == 0
    if (dp[idx][tight][sum] != -1):
        return dp[idx][tight][sum]
    ans = 0
    for d in range(10):
        newTight = False
        if (tight and ord(st[idx]) - ord('0') < d):
            continue
        if (tight and ord(st[idx]) - ord('0') == d):
            newTight = True
        if (sum >= d):
            ans += recursive(idx + 1, sum - d, newTight, st, dp, num)
    dp[idx][tight][sum] = ans
    return dp[idx][tight][sum]


def formArray(N):
    dp = [[[-1 for x in range(166)]for y in range(2)]for z in range(20)]
    st = str(N)
    num = len(st)
    arr = []
    for i in range(1, 163):
        arr .append(recursive(0, i, 1, st, dp, num))
    return arr


def findPair(a, b):
    arr_smaller = formArray(a - 1)
    arr_greater = formArray(b)
    for i in range(len(arr_greater)):
        arr_greater[i] -= arr_smaller[i]
    ans = 0
    for i in range(1, 163):
        for j in range(i + 1, 163):
            if (math .gcd(i, j) == 1):
                ans = (ans + arr_greater[i - 1] * arr_greater[j - 1])
    return ans


if __name__ == "__main__":
    a = 12
    b = 15
    print(findPair(a, b))

# Expected output:
4
# semiperfect number | python3 program to check if the number is semi - perfect or not ; code to find all the factors of the number excluding the number itself ; vector to store the factors ; note that this loop runs till sqrt ( n ) ; if the value of i is a factor ; condition to check the divisor is not the number itself ; return the vector ; function to check if the number is semi - perfect or not ; find the divisors ; sorting the vector ; subset to check if no is semiperfect ; initialising 1 st column to true ; initializing 1 st row except zero position to 0 ; loop to find whether the number is semiperfect ; calculation to check if the number can be made by summation of divisors ; if not possible to make the number by any combination of divisors ; 

import math


def factors(n):
    v = []
    v .append(1)
    sqt = int(math .sqrt(n))
    for i in range(2, sqt + 1):
        if (n % i == 0):
            v .append(i)
            if (n // i != i):
                v .append(n // i)
    return v


def check(n):
    v = []
    v = sorted(factors(n))
    r = len(v)
    subset = [[0 for i in range(n + 1)]for j in range(r + 1)]
    for i in range(r + 1):
        subset[i][0] = True
    for i in range(1, n + 1):
        subset[0][i] = False
    for i in range(1, r + 1):
        for j in range(1, n + 1):
            if (j < v[i - 1]):
                subset[i][j] = subset[i - 1][j]
            else:
                subset[i][j] = (subset[i - 1][j]
                                or subset[i - 1][j - v[i - 1]])
    if ((subset[r][n]) == 0):
        return False
    else:
        return True


if __name__ == "__main__":
    n = 40
    if (check(n)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# minimum cost to reach the top of the floor by climbing stairs | function to find the minimum cost to reach n - th floor ; declare an array ; base case ; initially to climb till 0 - th or 1 th stair ; iterate for finding the cost ; return the minimum ; 
def minimumCost(cost, n):
    dp = [None] * n
    if n == 1:
        return cost[0]
    dp[0] = cost[0]
    dp[1] = cost[1]
    for i in range(2, n):
        dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i]
    return min(dp[n - 2], dp[n - 1])


if __name__ == "__main__":
    a = [16, 19, 10, 12, 18]
    n = len(a)
    print(minimumCost(a, n))

# Expected output:
31
# minimum cost to reach the top of the floor by climbing stairs | function to find the minimum cost to reach n - th floor ; traverse till n - th stair ; update the last two stairs value ; 
def minimumCost(cost, n):
    dp1 = 0
    dp2 = 0
    for i in range(n):
        dp0 = cost[i] + min(dp1, dp2)
        dp2 = dp1
        dp1 = dp0
    return min(dp1, dp2)


if __name__ == "__main__":
    a = [2, 5, 3, 1, 7, 3, 4]
    n = len(a)
    print(minimumCost(a, n))

# Expected output:
9
# sudo placement [ 1.5 ] | wolfish | python program for sp - wolfish ; function to find the maxcost of path from ( n - 1 , n - 1 ) to ( 0 , 0 ) ; base condition ; reaches the point ; if the state has been visited previously ; i + j ; check if it is a power of 2 , then only move diagonally ; if not a power of 2 then move side - wise ; function to return the maximum cost ; calling dp function to get the answer ; 

size = 1000


def maxCost(a, m, n, dp):
    if (n < 0 or m < 0):
        return int(-1e9)
    elif (m == 0 and n == 0):
        return 0
    elif (dp[m][n] != -1):
        return dp[m][n]
    else:
        num = m + n
        if ((num & (num - 1)) == 0):
            dp[m][n] = a[m][n] + maxCost(a, m - 1, n - 1, dp)
            return dp[m][n]
        else:
            dp[m][n] = (a[m][n] + max(maxCost(a, m - 1, n, dp),
                        maxCost(a, m, n - 1, dp)))
            return dp[m][n]


def answer(a, n):
    dp = [[0 for i in range(size)]for j in range(size)]
    for i in range(size):
        for j in range(size):
            dp[i][j] = -1
    return maxCost(a, n - 1, n - 1, dp)


if __name__ == '__main__':
    a = [[1, 2, 3, 1], [4, 5, 6, 1], [7, 8, 9, 1], [1, 1, 1, 1]]
    n = 4
    print(answer(a, n))

# Expected output:
16
# edit distance and lcs ( longest common subsequence ) | python 3 program to find edit distance ( when only two operations are allowed , insert and delete ) using lcs . ; find lcs ; edit distance is delete operations + insert operations . ; 
def editDistanceWith2Ops(X, Y):
    m = len(X)
    n = len(Y)
    L = [[0 for x in range(n + 1)]for y in range(m + 1)]
    for i in range(m + 1):
        for j in range(n + 1):
            if (i == 0 or j == 0):
                L[i][j] = 0
            elif (X[i - 1] == Y[j - 1]):
                L[i][j] = L[i - 1][j - 1] + 1
            else:
                L[i][j] = max(L[i - 1][j], L[i][j - 1])
    lcs = L[m][n]
    return (m - lcs) + (n - lcs)


if __name__ == "__main__":
    X = "abc"
    Y = "acd"
    print(editDistanceWith2Ops(X, Y))

# Expected output:
2
# longest common subsequence | dp using memoization | returns length of lcs for x [ 0. . m - 1 ] , y [ 0. . n - 1 ] ; 
def lcs(X, Y, m, n):
    if (m == 0 or n == 0):
        return 0
    if (X[m - 1] == Y[n - 1]):
        return 1 + lcs(X, Y, m - 1, n - 1)
    else:
        return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n))


if __name__ == '__main__':
    X = "AGGTAB"
    Y = "GXTXAYB"
    m = len(X)
    n = len(Y)
    print("Length of LCS:", lcs(X, Y, m, n))

# Expected output:
Length of LCS: 4
# number of different cyclic paths of length n in a tetrahedron | function to count the number of steps in a tetrahedron ; initially coming to b is b -> b ; cannot reach a , d or c ; iterate for all steps ; recurrence relation ; memoize previous values ; returns steps ; 
def countPaths(n):
    zB = 1
    zADC = 0
    for i in range(1, n + 1):
        nzB = zADC * 3
        nzADC = (zADC * 2 + zB)
        zB = nzB
        zADC = nzADC
    return zB


n = 3
print(countPaths(n))

# Expected output:
6
# minimum steps to reach target by a knight | set 2 | initializing the matrix . ; if knight is on the target position return 0. ; if already calculated then return that value . taking absolute difference . ; there will be two distinct positions from the knight towards a target . if the target is in same row or column as of knight than there can be four positions towards the target but in that two would be the same and the other two would be the same . ; ( x1 , y1 ) and ( x2 , y2 ) are two positions . these can be different according to situation . from position of knight , the chess board can be divided into four blocks i . e . . n - e , e - s , s - w , w - n . ; ans will be , 1 + minimum of steps required from ( x1 , y1 ) and ( x2 , y2 ) . ; exchanging the coordinates x with y of both knight and target will result in same ans . ; 

dp = [[0 for i in range(8)]for j in range(8)]


def getsteps(x, y, tx, ty):
    if (x == tx and y == ty):
        return dp[0][0]
    elif (dp[abs(x - tx)][abs(y - ty)] != 0):
        return dp[abs(x - tx)][abs(y - ty)]
    else:
        x1, y1, x2, y2 = 0, 0, 0, 0
        if (x <= tx):
            if (y <= ty):
                x1 = x + 2
                y1 = y + 1
                x2 = x + 1
                y2 = y + 2
            else:
                x1 = x + 2
                y1 = y - 1
                x2 = x + 1
                y2 = y - 2
        elif (y <= ty):
            x1 = x - 2
            y1 = y + 1
            x2 = x - 1
            y2 = y + 2
        else:
            x1 = x - 2
            y1 = y - 1
            x2 = x - 1
            y2 = y - 2
        dp[abs(x - tx)][abs(y - ty)] = min(getsteps(x1,
                                                    y1, tx, ty), getsteps(x2, y2, tx, ty)) + 1
        dp[abs(y - ty)][abs(x - tx)] = dp[abs(x - tx)][abs(y - ty)]
        return dp[abs(x - tx)][abs(y - ty)]


if __name__ == '__main__':
    n = 100
    x = 4
    y = 5
    tx = 1
    ty = 1
    if ((x == 1 and y == 1 and tx == 2 and ty == 2) or (
            x == 2 and y == 2 and tx == 1 and ty == 1)):
        ans = 4
    elif ((x == 1 and y == n and tx == 2 and ty == n - 1) or (x == 2 and y == n - 1 and tx == 1 and ty == n)):
        ans = 4
    elif ((x == n and y == 1 and tx == n - 1 and ty == 2) or (x == n - 1 and y == 2 and tx == n and ty == 1)):
        ans = 4
    elif ((x == n and y == n and tx == n - 1 and ty == n - 1) or (x == n - 1 and y == n - 1 and tx == n and ty == n)):
        ans = 4
    else:
        dp[1][0] = 3
        dp[0][1] = 3
        dp[1][1] = 2
        dp[2][0] = 2
        dp[0][2] = 2
        dp[2][1] = 1
        dp[1][2] = 1
        ans = getsteps(x, y, tx, ty)
    print(ans)

# Expected output:
3
# number of subsets with sum divisible by m | use dynamic programming to find sum of subsequences . ; find sum pf array elements ; dp [ i ] [ j ] would be > 0 if arr [ 0. . i - 1 ] has a subsequence with sum equal to j . ; there is always sum equals zero ; fill up the dp table ; initialize the counter ; check if the sum exists ; check sum is divisible by m ; 
def sumSubSequence(arr, length, m):
    summ = 0
    for i in arr:
        summ += i
    dp = [[0 for i in range(summ + 1)]for j in range(length + 1)]
    for i in range(length + 1):
        dp[i][0] += 1
    for i in range(1, length + 1):
        dp[i][arr[i - 1]] += 1
        for j in range(1, summ + 1):
            if dp[i - 1][j] > 0:
                dp[i][j] += 1
                dp[i][j + arr[i - 1]] += 1
    count = 0
    for i in range(1, summ + 1):
        if dp[length][i] > 0:
            if i % m == 0:
                count += dp[length][i]
    return count


if __name__ == "__main__":
    arr = [1, 2, 3]
    m = 3
    length = len(arr)
    print(sumSubSequence(arr, length, m))

# Expected output:
3
# longest decreasing subsequence | function that returns the length of the longest decreasing subsequence ; initialize lds with 1 for all index the minimum lds starting with any element is always 1 ; compute lds from every index in bottom up manner ; select the maximum of all the lds values ; returns the length of the lds ; 
def lds(arr, n):
    lds = [0] * n
    max = 0
    for i in range(n):
        lds[i] = 1
    for i in range(1, n):
        for j in range(i):
            if (arr[i] < arr[j] and lds[i] < lds[j] + 1):
                lds[i] = lds[j] + 1
    for i in range(n):
        if (max < lds[i]):
            max = lds[i]
    return max


if __name__ == "__main__":
    arr = [15, 27, 14, 38, 63, 55, 46, 65, 85]
    n = len(arr)
    print("Length of LDS is", lds(arr, n))

# Expected output:
Length of LDS is 3