giulio98/xlcost-single-prompt huggingface dataset:
# minimum count of elements that sums to a given number | python3 implementation of the above approach ; we will only store min counts of sum upto 100 ; memo [ 0 ] = 0 as 0 is made from 0 elements ; fill memo array with min counts of elements that will constitute sum upto 100 ; min_count will store min count of elements chosen ; starting from end iterate over each 2 digits and add min count of elements to min_count ; 
def minCount(K):
    memo = [10 ** 9 for i in range(100)]
    memo[0] = 0
    for i in range(1, 100):
        memo[i] = min(memo[i - 1] + 1, memo[i])
    for i in range(10, 100):
        memo[i] = min(memo[i - 10] + 1, memo[i])
    for i in range(25, 100):
        memo[i] = min(memo[i - 25] + 1, memo[i])
    min_count = 0
    while (K > 0):
        min_count += memo[K % 100]
        K //= 100
    return min_count


K = 69
print(minCount(K))

# Expected output:
9
# number of sub | python3 implementation of the approach ; function to return the number of subsequences which have at least one consecutive pair with difference less than or equal to 1 ; not required sub - sequences which turn required on adding i ; required sub - sequence till now will be required sequence plus sub - sequence which turns required ; similarly for not required ; also updating total required and not required sub - sequences ; also , storing values in dp ; 

import numpy as np
N = 10000


def count_required_sequence(n, arr):
    total_required_subsequence = 0
    total_n_required_subsequence = 0
    dp = np .zeros((N, 2))
    for i in range(n):
        turn_required = 0
        for j in range(-1, 2, 1):
            turn_required += dp[arr[i] + j][0]
        required_end_i = (total_required_subsequence + turn_required)
        n_required_end_i = (1 + total_n_required_subsequence - turn_required)
        total_required_subsequence += required_end_i
        total_n_required_subsequence += n_required_end_i
        dp[arr[i]][1] += required_end_i
        dp[arr[i]][0] += n_required_end_i
    return total_required_subsequence


if __name__ == "__main__":
    arr = [1, 6, 2, 1, 9]
    n = len(arr)
    print(count_required_sequence(n, arr))

# Expected output:
12.0
# number of ways to choose elements from the array such that their average is k | python implementation of above approach ; initialize dp array by - 1 ; base cases index can 't be less than 0 ; no element is picked hence average cannot be calculated ; if remainder is non zero , we cannot divide the sum by count i . e . the average will not be an integer ; if we find an average return 1 ; if we have already calculated this function simply return it instead of calculating it again ; if we don 't pick the current element  simple recur for index -1 ; if we pick the current element add it to our current sum and increment count by 1 ; store the value for the current function ; function to return the number of ways ; push - 1 at the beginning to make it 1 - based indexing ; call recursive function waysutil to calculate total ways ; 

import numpy as np
MAX_INDEX = 51
MAX_SUM = 2505
dp = np .ones((MAX_INDEX, MAX_SUM, MAX_INDEX)) * -1


def waysutil(index, sum, count, arr, K):
    if (index < 0):
        return 0
    if (index == 0):
        if (count == 0):
            return 0
        remainder = sum % count
        if (remainder != 0):
            return 0
        average = sum // count
        if (average == K):
            return 1
    if (dp[index][sum][count] != -1):
        return dp[index][sum][count]
    dontpick = waysutil(index - 1, sum, count, arr, K)
    pick = waysutil(index - 1, sum + arr[index], count + 1, arr, K)
    total = pick + dontpick
    dp[index][sum][count] = total
    return total


def ways(N, K, arr):
    Arr = []
    Arr .append(-1)
    for i in range(N):
        Arr .append(arr[i])
    answer = waysutil(N, 0, 0, Arr, K)
    return answer


if __name__ == "__main__":
    arr = [3, 6, 2, 8, 7, 6, 5, 9]
    N = len(arr)
    K = 5
    print(ways(N, K, arr))

# Expected output:
19.0
# subset with sum closest to zero | python3 code for above implementation ; variable to store states of dp ; function to return the number closer to integer s ; to find the sum closest to zero since sum can be negative , we will add max to it to make it positive ; base cases ; checks if a state is already solved ; recurrence relation ; returning the value ; function to calculate the closest sum value ; calculate the closest value for every subarray arr [ i - 1 : n ] ; 

import numpy as np
arrSize = 51
maxSum = 201
MAX = 100
inf = 999999
dp = np .zeros((arrSize, maxSum))
visit = np .zeros((arrSize, maxSum))


def RetClose(a, b, s):
    if (abs(a - s) < abs(b - s)):
        return a
    else:
        return b


def MinDiff(i, sum, arr, n):
    if (i == n):
        return 0
    if (visit[i][sum + MAX]):
        return dp[i][sum + MAX]
    visit[i][sum + MAX] = 1
    dp[i][sum +
          MAX] = RetClose(arr[i] +
                          MinDiff(i +
                                  1, sum +
                                  arr[i], arr, n), MinDiff(i +
                                                           1, sum, arr, n), -
                          1 *
                          sum)
    return dp[i][sum + MAX]


def FindClose(arr, n):
    ans = inf
    for i in range(1, n + 1):
        ans = RetClose(arr[i - 1] + MinDiff(i, arr[i - 1], arr, n), ans, 0)
    print(ans)


if __name__ == "__main__":
    arr = [25, -9, -10, -4, -7, -33]
    n = len(arr)
    FindClose(arr, n)

# Expected output:
-1.0
# distinct palindromic sub | python3 implementation of the approach ; function to return the count of distinct palindromic sub - strings of the given string s ; to store the positions of palindromic sub - strings ; map to store the sub - strings ; sub - strings of length 1 are palindromes ; store continuous palindromic sub - strings ; store palindromes of size 2 ; if str [ i ... ( i + 1 ) ] is not a palindromic then set dp [ i ] [ i + 1 ] = 0 ; find palindromic sub - strings of length >= 3 ; end of palindromic substring ; if s [ start ] = = s [ end ] and dp [ start + 1 ] [ end - 1 ] is already palindrome then s [ start ... . end ] is also a palindrome ; set dp [ start ] [ end ] = 1 ; not a palindrome ; return the count of distinct palindromes ; 

import numpy as np


def palindromeSubStrs(s):
    dp = np .zeros((len(s), len(s)))
    m = {}
    for i in range(len(s)):
        dp[i][i] = 1
        m[s[i:i + 1]] = 1
    for i in range(len(s) - 1):
        if (s[i] == s[i + 1]):
            dp[i][i + 1] = 1
            m[s[i:i + 2]] = 1
        else:
            dp[i][i + 1] = 0
    for length in range(3, len(s) + 1):
        for st in range(len(s) - length + 1):
            end = st + length - 1
            if (s[st] == s[end] and dp[st + 1][end - 1]):
                dp[st][end] = 1
                m[s[st:end + 1]] = 1
            else:
                dp[st][end] = 0
    return len(m)


if __name__ == "__main__":
    s = "abaaa"
    print(palindromeSubStrs(s))

# Expected output:
5
# maximum sum path in a matrix from top to bottom and back | python 3 implementation of the approach ; input matrix ; dp matrix ; function to return the sum of the cells arr [ i1 ] [ j1 ] and arr [ i2 ] [ j2 ] ; recursive function to return the required maximum cost path ; column number of second path ; base case ; if already calculated , return from dp matrix ; recurring for neighbouring cells of both paths together ; saving result to the dp matrix for current state ; 

import sys
n = 4
m = 4
arr = [[1, 0, 3, -1], [3, 5, 1, -2], [-2, 0, 1, 1], [2, 1, -1, 1]]
cache = [[[-1 for i in range(5)]for j in range(5)]for k in range(5)]


def sum(i1, j1, i2, j2):
    if (i1 == i2 and j1 == j2):
        return arr[i1][j1]
    return arr[i1][j1] + arr[i2][j2]


def maxSumPath(i1, j1, i2):
    j2 = i1 + j1 - i2
    if (i1 >= n or i2 >= n or j1 >= m or j2 >= m):
        return 0
    if (cache[i1][j1][i2] != -1):
        return cache[i1][j1][i2]
    ans = -sys .maxsize - 1
    ans = max(ans, maxSumPath(i1 + 1, j1, i2 + 1) + sum(i1, j1, i2, j2))
    ans = max(ans, maxSumPath(i1, j1 + 1, i2) + sum(i1, j1, i2, j2))
    ans = max(ans, maxSumPath(i1, j1 + 1, i2 + 1) + sum(i1, j1, i2, j2))
    ans = max(ans, maxSumPath(i1 + 1, j1, i2) + sum(i1, j1, i2, j2))
    cache[i1][j1][i2] = ans
    return ans


if __name__ == '__main__':
    print(maxSumPath(0, 0, 0))

# Expected output:
16
# bellman ford algorithm ( simple implementation ) | python3 program for bellman - ford 's single source shortest path algorithm. ; the main function that finds shortest distances from src to all other vertices using bellman - ford algorithm . the function also detects negative weight cycle the row graph [ i ] represents i - th edge with three values u , v and w . ; initialize distance of all vertices as infinite . ; initialize distance of source as 0 ; relax all edges | v | - 1 times . a simple shortest path from src to any other vertex can have at - most | v | - 1 edges ; check for negative - weight cycles . the above step guarantees shortest distances if graph doesn 't contain  negative weight cycle. if we get a  shorter path, then there is a cycle. ; 

from sys import maxsize


def BellmanFord(graph, V, E, src):
    dis = [maxsize] * V
    dis[src] = 0
    for i in range(V - 1):
        for j in range(E):
            if dis[graph[j][0]] + graph[j][2] < dis[graph[j][1]]:
                dis[graph[j][1]] = dis[graph[j][0]] + graph[j][2]
    for i in range(E):
        x = graph[i][0]
        y = graph[i][1]
        weight = graph[i][2]
        if dis[x] != maxsize and dis[x] + weight < dis[y]:
            print("Graph contains negative weight cycle")
    return dis, V


if __name__ == "__main__":
    V = 5
    E = 8

    graph = [[0, 1, -1], [0, 2, 4], [1, 2, 3],
             [1, 3, 2], [1, 4, 2], [3, 2, 5],
             [3, 1, 1], [4, 3, -3]]
    dis, V = BellmanFord(graph, V, E, 0)
    for i in range(V):
        print("%d		%d" % (i, dis[i]))

# Expected output:
0		0
1		-1
2		2
3		-2
4		1
# find number of edges that can be broken in a tree such that bitwise or of resulting two trees are equal | python3 implementation of the approach ; function to perform simple dfs ; finding the number of times each bit is set in all the values of a subtree rooted at v ; checking for each bit whether the numbers with that particular bit as set are either zero in both the resulting trees or greater than zero in both the resulting trees ; 

m, x = [0] * 1000, [0] * 22
a = [[0 for i in range(22)]for j in range(1000)]
ans = 0


def dfs(u, p):
    global ans
    for i in range(0, len(g[u])):
        v = g[u][i]
        if v != p:
            dfs(v, u)
            for i in range(0, 22):
                a[u][i] += a[v][i]
    pp = 0
    for i in range(0, 22):
        if (not ((a[u][i] > 0 and x[i] - a[u][i] > 0)
                 or (a[u][i] == 0 and x[i] == 0))):
            pp = 1
            break
    if pp == 0:
        ans += 1


if __name__ == "__main__":
    n = 4
    g = [[]for i in range(n + 1)]
    m[1] = 1
    m[2] = 3
    m[3] = 2
    m[4] = 3
    for i in range(1, n + 1):
        y, k = m[i], 0
        while y != 0:
            p = y % 2
            if p == 1:
                x[k] += 1
                a[i][k] += 1
            y = y // 2
            k += 1
    g[1].append(2)
    g[2].append(1)
    g[1].append(3)
    g[3].append(1)
    g[1].append(4)
    g[4].append(1)
    dfs(1, 0)
    print(ans)

# Expected output:
2
# minimum cost to reach end of array array when a maximum jump of k index is allowed | python3 implementation of the approach ; for calculating the number of elements ; allocating memo table and initializing with int_max ; base case ; for every element relax every reachable element ie relax next k elements ; reaching next k element ; relaxing the element ; return the last element in the array ; 

import sys


def minCostJumpsDP(A, k):
    size = len(A)
    x = [sys .maxsize] * (size)
    x[0] = 0
    for i in range(size):
        j = i + 1
        while j < i + k + 1 and j < size:
            x[j] = min(x[j], x[i] + abs(A[i] - A[j]))
            j += 1
    return x[size - 1]


if __name__ == "__main__":
    input_ = [83, 26, 37, 35, 33, 35, 56]
    print(minCostJumpsDP(input_, 3))

# Expected output:
69
# dp on trees | set | function to find the diameter of the tree using dynamic programming ; store the first maximum and secondmax ; traverse for all children of node ; call dfs function again ; find first max ; secondmaximum ; elif dp1 [ i ] > secondmax : find secondmaximum ; base case for every node ; if firstmax != - 1 : add ; find dp [ 2 ] ; return maximum of both ; 
def dfs(node, parent, dp1, dp2, adj):
    firstmax, secondmax = -1, -1
    for i in adj[node]:
        if i == parent:
            continue
        dfs(i, node, dp1, dp2, adj)
        if firstmax == -1:
            firstmax = dp1[i]
        elif dp1[i] >= firstmax:
            secondmax = firstmax
            firstmax = dp1[i]
            secondmax = dp1[i]
    dp1[node] = 1
    dp1[node] += firstmax
    if secondmax != -1:
        dp2[node] = 1 + firstmax + secondmax
    return max(dp1[node], dp2[node])


if __name__ == "__main__":
    n, diameter = 5, -1
    adj = [[]for i in range(n + 1)]
    adj[1].append(2)
    adj[2].append(1)
    adj[1].append(3)
    adj[3].append(1)
    adj[2].append(4)
    adj[4].append(2)
    adj[2].append(5)
    adj[5].append(2)
    dp1 = [0] * (n + 1)
    dp2 = [0] * (n + 1)
    print("Diameter of the given tree is", dfs(1, 1, dp1, dp2, adj))

# Expected output:
Diameter of the given tree is 2
# find sub | python implementation of the approach ; function to return the sum of the sub - matrix ; function that returns true if it is possible to find the sub - matrix with required sum ; 2 - d array to store the sum of all the sub - matrices ; filling of dp [ ] [ ] array ; checking for each possible sub - matrix of size k x k ; sub - matrix with the given sum not found ; 

N = 4


def getSum(r1, r2, c1, c2, dp):
    return dp[r2][c2] - dp[r2][c1] - dp[r1][c2] + dp[r1][c1]


def sumFound(K, S, grid):
    dp = [[0 for i in range(N + 1)]for j in range(N + 1)]
    for i in range(N):
        for j in range(N):
            dp[i + 1][j + 1] = dp[i + 1][j] + \
                dp[i][j + 1] - dp[i][j] + grid[i][j]
    for i in range(0, N):
        for j in range(0, N):
            sum = getSum(i, i + K, j, j + K, dp)
            if (sum == S):
                return True
    return False


grid = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
K = 2
S = 14
if (sumFound(K, S, grid)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# stepping numbers | prints all stepping numbers reachable from num and in range [ n , m ] ; queue will contain all the stepping numbers ; get the front element and pop from the queue ; if the stepping number is in the range [ n , m ] then display ; if stepping number is 0 or greater than m , no need to explore the neighbors ; get the last digit of the currently visited stepping number ; there can be 2 cases either digit to be appended is lastdigit + 1 or lastdigit - 1 ; if lastdigit is 0 then only possible digit after 0 can be 1 for a stepping number ; if lastdigit is 9 then only possible digit after 9 can be 8 for a stepping number ; prints all stepping numbers in range [ n , m ] using bfs . ; for every single digit number ' i ' find all the stepping numbers starting with i ; 
def bfs(n, m, num):
    q = []
    q .append(num)
    while len(q) > 0:
        stepNum = q[0]
        q .pop(0)
        if (stepNum <= m and stepNum >= n):
            print(stepNum, end=" ")
        if (num == 0 or stepNum > m):
            continue
        lastDigit = stepNum % 10
        stepNumA = stepNum * 10 + (lastDigit - 1)
        stepNumB = stepNum * 10 + (lastDigit + 1)
        if (lastDigit == 0):
            q .append(stepNumB)
        elif (lastDigit == 9):
            q .append(stepNumA)
        else:
            q .append(stepNumA)
            q .append(stepNumB)


def displaySteppingNumbers(n, m):
    for i in range(10):
        bfs(n, m, i)


n, m = 0, 21
displaySteppingNumbers(n, m)

# Expected output:
0 1 10 12 2 21 3 4 5 6 7 8 9
# minimum number of operations required to sum to binary string s | function to return the minimum operations required to sum to a number reprented by the binary string s ; reverse the string to consider it from lsb to msb ; initialise the dp table ; if s [ 0 ] = '0' , there is no need to perform any operation ; if s [ 0 ] = '1' , just perform a single operation ( i . e add 2 ^ 0 ) ; irrespective of the lsb , dp [ 0 ] [ 1 ] is always 1 as there is always the need of making the suffix of the binary string of the form "11 . . . . 1" as suggested by the definition of dp [ i ] [ 1 ] ; transition from dp [ i - 1 ] [ 0 ] ; 1. transition from dp [ i - 1 ] [ 1 ] by just doing 1 extra operation of subtracting 2 ^ i 2. transition from dp [ i - 1 ] [ 0 ] by just doing 1 extra operation of subtracting 2 ^ ( i + 1 ) ; transition from dp [ i - 1 ] [ 1 ] ; 1. transition from dp [ i - 1 ] [ 1 ] by just doing 1 extra operation of adding 2 ^ ( i + 1 ) 2. transition from dp [ i - 1 ] [ 0 ] by just doing 1 extra operation of adding 2 ^ i ; 
def findMinOperations(S):
    S = S[::-1]
    n = len(S)
    dp = [[0] * 2] * (n + 1)
    if (S[0] == '0'):
        dp[0][0] = 0
    else:
        dp[0][0] = 1
    dp[0][1] = 1
    for i in range(1, n):
        if (S[i] == '0'):
            dp[i][0] = dp[i - 1][0]
            dp[i][1] = 1 + min(dp[i - 1][1], dp[i - 1][0])
        else:
            dp[i][1] = dp[i - 1][1]
            dp[i][0] = 1 + min(dp[i - 1][0], dp[i - 1][1])
    return dp[n - 1][0]


if __name__ == "__main__":
    S = "100"
    print(findMinOperations(S))
    S = "111"
    print(findMinOperations(S))

# Expected output:
1
2
# k | function that finds the nth element of k - fibonacci series ; if n is less than k then the element is '1 ; first k elements are 1 ; ( k + 1 ) th element is k ; find the elements of the k - fibonacci series ; subtract the element at index i - k - 1 and add the element at index i - i from the sum ( sum contains the sum of previous ' k ' elements ) ; set the new sum ; 
def solve(N, K):
    Array = [0] * (N + 1)
    if (N <= K):
        print("1")
        return
    i = 0
    sm = K
    for i in range(1, K + 1):
        Array[i] = 1
    Array[i + 1] = sm
    for i in range(K + 2, N + 1):
        Array[i] = sm - Array[i - K - 1]+Array[i - 1]
        sm = Array[i]
    print(Array[N])


N = 4
K = 2
solve(N, K)

# Expected output:
3
# minimum sum possible of any bracket sequence of length n | python 3 program to find the minimum sum possible of any bracket sequence of length n using the given values for brackets ; dp array ; recursive function to check for correct bracket expression ; not a proper bracket expression ; if reaches at end ; if proper bracket expression ; if not , return max ; if already visited ; to find out minimum sum ; 

MAX_VAL = 10000000
dp = [[-1 for i in range(100)]for i in range(100)]


def find(index, openbrk, n, adj):
    if (openbrk < 0):
        return MAX_VAL
    if (index == n):
        if (openbrk == 0):
            return 0
        else:
            return MAX_VAL
    if (dp[index][openbrk] != -1):
        return dp[index][openbrk]
    dp[index][openbrk] = min(
        adj[index][1] +
        find(
            index +
            1,
            openbrk +
            1,
            n,
            adj),
        adj[index][0] +
        find(
            index +
            1,
            openbrk -
            1,
            n,
            adj))
    return dp[index][openbrk]


if __name__ == '__main__':
    n = 4
    adj = [[5000, 3000], [6000, 2000], [8000, 1000], [9000, 6000]]
    print(find(1, 1, n, adj) + adj[0][1])

# Expected output:
19000
# minimum cost to buy n kilograms of sweet for m persons | function to find the minimum cost of sweets ; defining the sweet array ; dp array to store the values ; since index starts from 1 we reassign the array into sweet ; assigning base cases for dp array ; at 0 it is free ; package not available for desirable amount of sweets ; buying the ' k ' kg package and assigning it to dp array ; if no solution , select from previous k - 1 packages ; if solution does not exist ; print the solution ; 
def find(m, n, adj):
    sweet = [0] * (n + 1)
    dp = [[[0 for i in range(n + 1)]for i in range(n + 1)]
          for i in range(n + 1)]
    sweet[0] = 0
    for i in range(1, m + 1):
        sweet[i] = adj[i - 1]
    for i in range(m + 1):
        for k in range(n + 1):
            dp[i][0][k] = 0
        for k in range(1, n + 1):
            dp[i][k][0] = -1
    for i in range(m + 1):
        for j in range(1, n + 1):
            for k in range(1, n + 1):
                dp[i][j][k] = -1
                if (i > 0 and j >= k and sweet[k] >
                        0 and dp[i - 1][j - k][k] != -1):
                    dp[i][j][k] = dp[i - 1][j - k][k] + sweet[k]
                if (dp[i][j][k] == -1 or (dp[i][j][k - 1]
                                          != -1 and dp[i][j][k] > dp[i][j][k - 1])):
                    dp[i][j][k] = dp[i][j][k - 1]
    if (dp[m][n][n] == -1):
        return 0
    else:
        return dp[m][n][n]


m = 3
adj = [2, 1, 3, 0, 4, 10]
n = len(adj)
print(find(m, n, adj))

# Expected output:
3
# maximum length of segments of 0 ' s ▁ and ▁ 1' s | recursive function to find total length of the array where 1 is greater than zero ; if reaches till end ; if dp is saved ; finding for each length ; if the character scanned is 1 ; if one is greater than zero , add total length scanned till now ; continue with next length ; return the value for start index ; 
def find(start, adj, n, dp):
    if (start == n):
        return 0
    if (dp[start] != -1):
        return dp[start]
    dp[start] = 0
    one = 0
    zero = 0
    for k in range(start, n, 1):
        if (adj[k] == '1'):
            one += 1
        else:
            zero += 1
        if (one > zero):
            dp[start] = max(dp[start], find(k + 1, adj, n, dp) + k - start + 1)
        else:
            dp[start] = max(dp[start], find(k + 1, adj, n, dp))
    return dp[start]


if __name__ == '__main__':
    adj = "100110001010001"
    n = len(adj)
    dp = [-1 for i in range(n + 1)]
    print(find(0, adj, n, dp))

# Expected output:
9
# length of longest common subsequence containing vowels | function to check whether ' ch ' is a vowel or not ; function to find the length of longest common subsequence which contains all vowel characters ; following steps build l [ m + 1 ] [ n + 1 ] in bottom up fashion . note that l [ i ] [ j ] contains length of lcs of x [ 0. . i - 1 ] and y [ 0. . j - 1 ] ; l [ m ] [ n ] contains length of lcs for x [ 0. . n - 1 ] and y [ 0. . m - 1 ] which contains all vowel characters ; 
def isVowel(ch):
    if (ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u'):
        return True
    return False


def lcs(X, Y, m, n):
    L = [[0 for i in range(n + 1)]for j in range(m + 1)]
    i, j = 0, 0
    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]) and isVowel(X[i - 1])):
                L[i][j] = L[i - 1][j - 1] + 1
            else:
                L[i][j] = max(L[i - 1][j], L[i][j - 1])
    return L[m][n]


X = "aieef"
Y = "klaief"
m = len(X)
n = len(Y)
print("Length of LCS =", lcs(X, Y, m, n))

# Expected output:
Length of LCS = 3