giulio98/xlcost-single-prompt huggingface dataset:
# check if a word exists in a grid or not | python3 program to check if the word exists in the grid or not ; function to check if a word exists in a grid starting from the first match in the grid level : index till which pattern is matched x , y : current position in 2d array ; pattern matched ; out of boundary ; if grid matches with a letter while recursion ; marking this cell as visited ; finding subpattern in 4 directions ; marking this cell as unvisited again ; else : not matching then false ; function to check if the word exists in the grid or not ; if total characters in matrix is less then pattern lenghth ; traverse in the grid ; if first letter matches , then recur and check ; 
def findmatch(mat, pat, x, y,
              nrow, ncol, level):

    l = len(pat)
    if (level == l):
        return True
    if (x < 0 or y < 0 or
            x >= nrow or y >= ncol):
        return False
    if (mat[x][y] == pat[level]):
        temp = mat[x][y]
        mat[x].replace(mat[x][y], "#")
        res = (findmatch(mat, pat, x - 1, y, nrow, ncol, level + 1) |
               findmatch(mat, pat, x + 1, y, nrow, ncol, level + 1) |
               findmatch(mat, pat, x, y - 1, nrow, ncol, level + 1) |
               findmatch(mat, pat, x, y + 1, nrow, ncol, level + 1))
        mat[x].replace(mat[x][y], temp)
        return res

    else:
        return False


def checkMatch(mat, pat, nrow, ncol):

    l = len(pat)
    if (l > nrow * ncol):
        return False
    for i in range(nrow):
        for j in range(ncol):
            if (mat[i][j] == pat[0]):
                if (findmatch(mat, pat, i, j,
                              nrow, ncol, 0)):
                    return True
    return False


if __name__ == "__main__":
    r = 4
    c = 4

    grid = ["axmy", "bgdf",
            "xeet", "raks"]
    if (checkMatch(grid, "geeks", r, c)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# construct an array from its pair | fills element in arr [ ] from its pair sum array pair [ ] . n is size of arr [ ] ; 
def constructArr(arr, pair, n):
    arr[0] = (pair[0] + pair[1] - pair[n - 1]) // 2
    for i in range(1, n):
        arr[i] = pair[i - 1] - arr[0]


if __name__ == '__main__':
    pair = [15, 13, 11, 10, 12, 10, 9, 8, 7, 5]
    n = 5
    arr = [0] * n
    constructArr(arr, pair, n)
    for i in range(n):
        print(arr[i], end=" ")

# Expected output:
8 7 5 3 2
# merge two sorted arrays with o ( 1 ) extra space | merge ar1 [ ] and ar2 [ ] with o ( 1 ) extra space ; iterate through all elements of ar2 [ ] starting from the last element ; find the smallest element greater than ar2 [ i ] . move all elements one position ahead till the smallest greater element is not found ; if there was a greater element ; 
def merge(ar1, ar2, m, n):
    for i in range(n - 1, -1, -1):
        last = ar1[m - 1]
        j = m - 2
        while (j >= 0 and ar1[j] > ar2[i]):
            ar1[j + 1] = ar1[j]
            j -= 1
        if (j != m - 2 or last > ar2[i]):
            ar1[j + 1] = ar2[i]
            ar2[i] = last


ar1 = [1, 5, 9, 10, 15, 20]
ar2 = [2, 3, 8, 13]
m = len(ar1)
n = len(ar2)
merge(ar1, ar2, m, n)
print("AfterMergingFirstArray:",  end="")
for i in range(m):
    print(ar1[i], " ", end="")
print("SecondArray:",  end="")
for i in range(n):
    print(ar2[i], " ", end="")

# Expected output:
AfterMergingFirstArray:1  2  3  5  8  9  SecondArray:10  13  15  20
# gould 's sequence | function to generate gould 's sequence ; loop to generate each row of pascal 's triangle up to nth row ; loop to generate each element of ith row ; if c is odd increment count ; print count of odd elements ; get n ; 
def gouldSequence(n):
    for row_num in range(1, n):
        count = 1
        c = 1
        for i in range(1, row_num):
            c = c * (row_num - i) / i
            if (c % 2 == 1):
                count += 1
        print(count, end=" ")


n = 16
gouldSequence(n)

# Expected output:
1 2 2 4 2 4 4 8 2 4 4 8 4 8 8
# product of maximum in first array and minimum in second | function to calculate the product ; sort the arrays to find the maximum and minimum elements in given arrays ; return product of maximum and minimum . ; 
def minmaxProduct(arr1, arr2, n1, n2):
    arr1 .sort()
    arr2 .sort()
    return arr1[n1 - 1] * arr2[0]


arr1 = [10, 2, 3, 6, 4, 1]
arr2 = [5, 1, 4, 2, 6, 9]
n1 = len(arr1)
n2 = len(arr2)
print(minmaxProduct(arr1, arr2, n1, n2))

# Expected output:
10
# minimum odd cost path in a matrix | python3 program to find minimum odd cost path in a matrix ; function to find the minimum cost ; leftmost element ; rightmost element ; any element except leftmost and rightmost element of a row is reachable from direct upper or left upper or right upper row 's block ; counting the minimum cost ; find the minimum cost ; 

M = 100
N = 100


def find_min_odd_cost(given, m, n):
    floor = [[0 for i in range(M)]for i in range(N)]
    min_odd_cost = 0
    i, j, temp = 0, 0, 0
    for j in range(n):
        floor[0][j] = given[0][j]
    for i in range(1, m):
        for j in range(n):
            if (j == 0):
                floor[i][j] = given[i][j]
                floor[i][j] += min(floor[i - 1][j], floor[i - 1][j + 1])
            elif (j == n - 1):
                floor[i][j] = given[i][j]
                floor[i][j] += min(floor[i - 1][j], floor[i - 1][j - 1])
            else:
                temp = min(floor[i - 1][j], floor[i - 1][j - 1])
                temp = min(temp, floor[i - 1][j + 1])
                floor[i][j] = given[i][j] + temp
    min_odd_cost = 10 ** 9
    for j in range(n):
        if (floor[n - 1][j] % 2 == 1):
            if (min_odd_cost > floor[n - 1][j]):
                min_odd_cost = floor[n - 1][j]
    if (min_odd_cost == -10 ** 9):
        return -1
    return min_odd_cost


m, n = 5, 5
given = [[1, 2, 3, 4, 6], [1, 2, 3, 4, 5], [
    1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [100, 2, 3, 4, 5]]
print("Minimum odd cost is", find_min_odd_cost(given, m, n))

# Expected output:
Minimum odd cost is 11
# product of maximum in first array and minimum in second | function to calculate the product ; initialize max of first array ; initialize min of second array ; to find the maximum element in first array ; to find the minimum element in second array ; process remaining elements ; 
def minMaxProduct(arr1, arr2, n1, n2):
    max = arr1[0]
    min = arr2[0]
    i = 1
    while (i < n1 and i < n2):
        if (arr1[i] > max):
            max = arr1[i]
        if (arr2[i] < min):
            min = arr2[i]
        i += 1
    while (i < n1):
        if (arr1[i] > max):
            max = arr1[i]
            i += 1
    while (i < n2):
        if (arr2[i] < min):
            min = arr2[i]
            i += 1
    return max * min


arr1 = [10, 2, 3, 6, 4, 1]
arr2 = [5, 1, 4, 2, 6, 9]
n1 = len(arr1)
n2 = len(arr1)
print(minMaxProduct(arr1, arr2, n1, n2))

# Expected output:
10
# search , insert and delete in an unsorted array | function to implement search operation ; 
def findElement(arr, n, key):
    for i in range(n):
        if (arr[i] == key):
            return i
    return -1


arr = [12, 34, 10, 6, 40]
n = len(arr)
key = 40
index = findElement(arr, n, key)
if index != -1:
    print("element found at position: " + str(index + 1))
else:
    print("element not found")

# Expected output:
element found at position: 5
# search , insert and delete in a sorted array | function to implement binary search ; low + ( high - low ) / 2 ; 
def binarySearch(arr, low, high, key):
    mid = (low + high) / 2
    if (key == arr[int(mid)]):
        return mid
    if (key > arr[int(mid)]):
        return binarySearch(arr, (mid + 1), high, key)
    if (key < arr[int(mid)]):
        return binarySearch(arr, low, (mid - 1), key)
    return 0


arr = [5, 6, 7, 8, 9, 10]
n = len(arr)
key = 10
print("Index:", int(binarySearch(arr, 0, n - 1, key)))

# Expected output:
Index: 5
# search , insert and delete in a sorted array | inserts a key in arr [ ] of given capacity . n is current size of arr [ ] . this function returns n + 1 if insertion is successful , else n . ; cannot insert more elements if n is already more than or equal to capcity ; 
def insertSorted(arr, n, key, capacity):
    if (n >= capacity):
        return n
    i = n - 1
    while i >= 0 and arr[i] > key:
        arr[i + 1] = arr[i]
        i -= 1
    arr[i + 1] = key
    return (n + 1)


arr = [12, 16, 20, 40, 50, 70]
for i in range(20):
    arr .append(0)
capacity = len(arr)
n = 6
key = 26
print("Before Insertion: ", end=" ")
for i in range(n):
    print(arr[i], end=" ")
n = insertSorted(arr, n, key, capacity)
print("AfterInsertion:",  end="")
for i in range(n):
    print(arr[i], end=" ")

# Expected output:
Before Insertion:  12 16 20 40 50 70 AfterInsertion:12 16 20 26 40 50 70
# search , insert and delete in a sorted array | to search a ley to be deleted ; function to delete an element ; find position of element to be deleted ; deleting element ; 
def binarySearch(arr, low, high, key):
    if (high < low):
        return -1
    mid = (low + high) // 2
    if (key == arr[mid]):
        return mid
    if (key > arr[mid]):
        return binarySearch(arr, (mid + 1), high, key)
    return binarySearch(arr, low, (mid - 1), key)


def deleteElement(arr, n, key):
    pos = binarySearch(arr, 0, n - 1, key)
    if (pos == -1):
        print("Element not found")
        return n
    for i in range(pos, n - 1):
        arr[i] = arr[i + 1]
    return n - 1


arr = [10, 20, 30, 40, 50]
n = len(arr)
key = 30
print("Array before deletion")
for i in range(n):
    print(arr[i], end=" ")
n = deleteElement(arr, n, key)
print("Arrayafterdeletion")
for i in range(n):
    print(arr[i], end=" ")

# Expected output:
Array before deletion
10 20 30 40 50 Arrayafterdeletion
10 20 40 50
# queries on number of binary sub | python 3 program to answer queries on number of submatrix of given size ; solve each query on matrix ; for each of the cell . ; finding submatrix size of oth row and column . ; intermediate cells . ; find frequency of each distinct size for 0 s and 1 s . ; find the cumulative sum . ; output the answer for each query ; 

MAX = 100
N = 5
M = 4


def solveQuery(n, m, mat, q, a, binary):
    dp = [[0 for x in range(m)]for y in range(n)]
    max = 1
    for i in range(n):
        for j in range(m):
            if (i == 0 or j == 0):
                dp[i][j] = 1
            elif ((mat[i][j] == mat[i - 1][j]) and (mat[i][j] == mat[i][j - 1]) and (mat[i][j] == mat[i - 1][j - 1])):
                dp[i][j] = (
                    min(dp[i - 1][j], min(dp[i - 1][j - 1], dp[i][j - 1])) + 1)
                if (max < dp[i][j]):
                    max = dp[i][j]
            else:
                dp[i][j] = 1
    freq0 = [0] * MAX
    freq1 = [0] * MAX
    for i in range(n):
        for j in range(m):
            if (mat[i][j] == 0):
                freq0[dp[i][j]] += 1
            else:
                freq1[dp[i][j]] += 1
    for i in range(max - 1, -1, -1):
        freq0[i] += freq0[i + 1]
        freq1[i] += freq1[i + 1]
    for i in range(q):
        if (binary[i] == 0):
            print(freq0[a[i]])
        else:
            print(freq1[a[i]])


if __name__ == "__main__":
    n = 5
    m = 4
    mat = [[0, 0, 1, 1], [0, 0, 1, 0], [
        0, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 1]]
    q = 2
    a = [2, 2]
    binary = [1, 0]
    solveQuery(n, m, mat, q, a, binary)

# Expected output:
4
1
# dynamic programming | wildcard pattern matching | linear time and constant space | function that matches input txt with given wildcard pattern ; empty pattern can only match with empty sting base case ; step 1 initialize markers : ; for step - ( 2 , 5 ) ; for step - ( 3 ) ; for step - ( 4 ) ; for step - ( 5 ) ; for step - ( 6 ) ; for step - ( 7 ) ; final check ; 
def stringmatch(txt, pat, n, m):
    if (m == 0):
        return (n == 0)
    i = 0
    j = 0
    index_txt = -1
    index_pat = -1
    while (i < n - 2):
        if (j < m and txt[i] == pat[j]):
            i += 1
            j += 1
        elif (j < m and pat[j] == '?'):
            i += 1
            j += 1
        elif (j < m and pat[j] == '*'):
            index_txt = i
            index_pat = j
            j += 1
        elif (index_pat != -1):
            j = index_pat + 1
            i = index_txt + 1
            index_txt += 1
        else:
            return False
    while (j < m and pat[j] == '*'):
        j += 1
    if (j == m):
        return True
    return False


strr = "baaabab"
pattern = "*****ba*****ab"
pattern = "ba*****ab"
pattern = "ba * ab"
pattern = "a*ab"
if (stringmatch(strr, pattern, len(strr), len(pattern))):
    print("Yes")
else:
    print("No")
pattern2 = "a*****ab"
if (stringmatch(strr, pattern2, len(strr), len(pattern2))):
    print("Yes")
else:
    print("No")

# Expected output:
No
No
# find n | function to find nth stern ' diatomic series ; initializing the dp array ; set the base case ; traversing the array from 2 nd element to nth element ; case 1 : for even n ; case 2 : for odd n ; 
def findSDSFunc(n):
    DP = [0] * (n + 1)
    DP[0] = 0
    DP[1] = 1
    for i in range(2, n + 1):
        if (int(i % 2) == 0):
            DP[i] = DP[int(i / 2)]
        else:
            DP[i] = (DP[int((i - 1) / 2)] + DP[int((i + 1) / 2)])
    return DP[n]


n = 15
print(findSDSFunc(n))

# Expected output:
4
# check if any valid sequence is divisible by m | python3 program to check if any valid sequence is divisible by m ; calculate modulo for this call ; base case ; check if sum is divisible by m ; check if the current state is already computed ; 1. try placing '+ ; 2. try placing '- ; calculate value of res for recursive case ; store the value for res for current states and return for parent call ; 
def isPossible(n, index, modulo, M, arr, dp):
    modulo = ((modulo % M) + M) % M
    if (index == n):
        if (modulo == 0):
            return 1
        return 0
    if (dp[index][modulo] != -1):
        return dp[index][modulo]

    placeAdd = isPossible(n, index+1, modulo+arr[index], M, arr, dp)
    placeMinus = isPossible(n, index + 1, modulo - arr[index], M, arr, dp)
    res = bool(placeAdd or placeMinus)
    dp[index][modulo] = res
    return res


MAX = 100
arr = [1, 2, 3, 4, 6]
n = len(arr)
M = 4
dp = [[-1] * (n + 1)] * MAX
res = isPossible(n, 1, arr[0], M, arr, dp)
if (res):
    print("True")
else:
    print("False")

# Expected output:
True
# dynamic programming on trees | set | python3 code to find the maximum path sum ; function for dfs traversal and to store the maximum value in dp [ ] for every node till the leaves ; initially dp [ u ] is always a [ u ] ; stores the maximum value from nodes ; traverse the tree ; if child is parent , then we continue without recursing further ; call dfs for further traversal ; store the maximum of previous visited node and present visited node ; add the maximum value returned to the parent node ; function that returns the maximum value ; 

dp = [0] * 100


def dfs(a, v, u, parent):
    dp[u] = a[u - 1]
    maximum = 0
    for child in v[u]:
        if child == parent:
            continue
        dfs(a, v, child, u)
        maximum = max(maximum, dp[child])
    dp[u] += maximum


def maximumValue(a, v):
    dfs(a, v, 1, 0)
    return dp[1]


def main():
    n = 14
    v = {}
    for i in range(n + 1):
        v[i] = []
    v[1].append(2), v[2].append(1)
    v[1].append(3), v[3].append(1)
    v[1].append(4), v[4].append(1)
    v[2].append(5), v[5].append(2)
    v[2].append(6), v[6].append(2)
    v[3].append(7), v[7].append(3)
    v[4].append(8), v[8].append(4)
    v[4].append(9), v[9].append(4)
    v[4].append(10), v[10].append(4)
    v[5].append(11), v[11].append(5)
    v[5].append(12), v[12].append(5)
    v[7].append(13), v[13].append(7)
    v[7].append(14), v[14].append(7)
    a = [3, 2, 1, 10, 1, 3, 9, 1, 5, 3, 4, 5, 9, 8]
    print(maximumValue(a, v))


main()

# Expected output:
22
# find position of an element in a sorted array of infinite numbers | binary search algorithm implementation ; function takes an infinite size array and a key to be searched and returns its position if found else - 1. we don 't know size of a[] and we can assume size to be infinite in this function. note that this function assumes a[] to be of infinite size therefore, there is no index out of bound checking ; find h to do binary search ; store previous high ; double high index ; update new val ; at this point we have updated low and high indices , thus use binary search between them ; 
def binary_search(arr, l, r, x):

    if r >= l:
        mid = l+(r-l)//2

        if arr[mid] == x:
            return mid

        if arr[mid] > x:
            return binary_search(arr, l, mid-1, x)

        return binary_search(arr, mid+1, r, x)

    return -1


def findPos(a, key):

    l, h, val = 0, 1, arr[0]
    while val < key:
        l = h
        h = 2*h
        val = arr[h]
    return binary_search(a, l, h, key)


arr = [3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170]
ans = findPos(arr, 10)
if ans == -1:
    print(("Element not found"))
else:
    print("Element found at index", ans)

# Expected output:
Element found at index 4
# count of possible hexagonal walks | python 3 implementation of counting number of possible hexagonal walks ; we initialize our origin with 1 ; for each n = 1 to 14 , we traverse in all possible direction . using this 3d array we calculate the number of ways at each step and the total ways for a given step shall be found at ways [ step number ] [ 8 ] [ 8 ] because all the steps after that will be used to trace back to the original point index 0 : 0 according to the image . ; this array stores the number of ways possible for a given step ; 

depth = 16
ways = [[[0 for i in range(17)]for i in range(17)]for i in range(17)]


def preprocess(list, steps):
    ways[0][8][8] = 1
    for N in range(1, 16, 1):
        for i in range(1, depth, 1):
            for j in range(1, depth, 1):
                ways[N][i][j] = (ways[N -
                                      1][i][j +
                                            1] +
                                 ways[N -
                                      1][i][j -
                                            1] +
                                 ways[N -
                                      1][i +
                                         1][j] +
                                 ways[N -
                                      1][i -
                                         1][j] +
                                 ways[N -
                                      1][i +
                                         1][j -
                                            1] +
                                 ways[N -
                                      1][i -
                                         1][j +
                                            1])
        list[N] = ways[N][8][8]
    print("Number of walks possible is/are", list[steps])


if __name__ == '__main__':
    list = [0 for i in range(16)]
    steps = 4
    preprocess(list, steps)

# Expected output:
Number of walks possible is/are 90
# check if possible to cross the matrix with given power | python3 program to find if it is possible to cross the matrix with given power ; for each value of dp [ i ] [ j ] [ k ] ; for first cell and for each value of k ; for first cell of each row ; for first cell of each column ; for rest of the cell ; down movement . ; right movement . ; diagonal movement . ; finding maximum k . ; 

N = 105
R = 3
C = 4


def maximumValue(n, m, p, grid):
    dp = [[[False for i in range(N)]for j in range(N)]for k in range(N)]
    for i in range(n):
        for j in range(m):
            k = grid[i][j]
            while (k <= p):
                if (i == 0 and j == 0):
                    if (k == grid[i][j]):
                        dp[i][j][k] = True
                elif (i == 0):
                    dp[i][j][k] = (dp[i][j][k] or dp[i][j - 1][k - grid[i][j]])
                elif (j == 0):
                    dp[i][j][k] = (dp[i][j][k] or dp[i - 1][j][k - grid[i][j]])
                else:
                    dp[i][j][k] = (dp[i][j][k] or dp[i][j - 1][k - grid[i][j]])
                    dp[i][j][k] = (dp[i][j][k] or dp[i - 1][j][k - grid[i][j]])
                    dp[i][j][k] = (dp[i][j][k] or dp[i - 1]
                                   [j - 1][k - grid[i][j]])
                k += 1
    ans = k
    while (ans >= 0):
        if (dp[n - 1][m - 1][ans]):
            break
        ans -= 1
    return ans


n = 3
m = 4
p = 9
grid = [[2, 3, 4, 1], [6, 5, 5, 3], [5, 2, 3, 4]]
print(maximumValue(n, m, p, grid))

# Expected output:
-1
# number of n digit stepping numbers | function that calculates the answer ; dp [ i ] [ j ] stores count of i digit stepping numbers ending with digit j . ; if n is 1 then answer will be 10. ; initialize values for count of digits equal to 1. ; compute values for count of digits more than 1. ; if ending digit is 0 ; if ending digit is 9 ; for other digits . ; stores the final answer ; 
def answer(n):
    dp = [[0 for x in range(10)]for y in range(n + 1)]
    if (n == 1):
        return 10
    for j in range(10):
        dp[1][j] = 1
    for i in range(2, n + 1):
        for j in range(10):
            if (j == 0):
                dp[i][j] = dp[i - 1][j + 1]
            elif (j == 9):
                dp[i][j] = dp[i - 1][j - 1]
            else:
                dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j + 1])
    sum = 0
    for j in range(1, 10):
        sum = sum + dp[n][j]
    return sum


n = 2
print(answer(n))

# Expected output:
17
# print longest palindromic subsequence | returns lcs x and y ; 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 ] ; following code is used to print lcs ; create a string length index + 1 and fill it with \ 0 ; start from the right - most - bottom - most corner and one by one store characters in lcs [ ] ; if current character in x [ ] and y are same , then current character is part of lcs ; put current character in result ; reduce values of i , j and index ; if not same , then find the larger of two and go in the direction of larger value ; returns longest palindromic subsequence of str ; find reverse of str ; return lcs of str and its reverse ; 
def lcs_(X, Y):
    m = len(X)
    n = len(Y)
    L = [[0] * (n + 1)] * (m + 1)
    for i in range(n + 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])
    index = L[m][n]
    lcs = [""] * (index + 1)
    i, j = m, n
    while (i > 0 and j > 0):
        if (X[i - 1] == Y[j - 1]):
            lcs[index - 1] = X[i - 1]
            i -= 1
            j -= 1
            index -= 1
        elif (L[i - 1][j] > L[i][j - 1]):
            i -= 1
        else:
            j -= 1
    ans = ""
    for x in range(len(lcs)):
        ans += lcs[x]
    return ans


def longestPalSubseq(string):
    rev = string[::-1]
    return lcs_(string, rev)


if __name__ == "__main__":
    string = "GEEKSFORGEEKS"
    print(longestPalSubseq(string))

# Expected output:
EESEE
# count all subsequences having product less than k | function to count numbers of such subsequences having product less than k . ; number of subsequence using j - 1 terms ; if arr [ j - 1 ] > i it will surely make product greater thus it won 't contribute then ; number of subsequence using 1 to j - 1 terms and j - th term ; 
def productSubSeqCount(arr, k):
    n = len(arr)
    dp = [[0 for i in range(n + 1)]for j in range(k + 1)]
    for i in range(1, k + 1):
        for j in range(1, n + 1):
            dp[i][j] = dp[i][j - 1]
            if arr[j - 1] <= i and arr[j - 1] > 0:
                dp[i][j] += dp[i // arr[j - 1]][j - 1] + 1
    return dp[k][n]


A = [1, 2, 3, 4]
k = 10
print(productSubSeqCount(A, k))

# Expected output:
11