giulio98/xlcost-single-prompt huggingface dataset:
# check if two expressions with brackets are same | python3 program to check if two expressions evaluate to same . ; return local sign of the operand . for example , in the expr a - b - ( c ) , local signs of the operands are + a , - b , + c ; evaluate expressions into the count vector of the 26 alphabets . if add is true , then add count to the count vector of the alphabets , else remove count from the count vector . ; stack stores the global sign for operands . ; + means true global sign is positive initially ; global sign for the bracket is pushed to the stack ; global sign is popped out which was pushed in for the last bracket ; global sign is positive ( we use different values in two calls of functions so that we finally check if all vector elements are 0. ; global sign is negative here ; returns true if expr1 and expr2 represent same expressions ; create a vector for all operands and initialize the vector as 0. ; put signs of all operands in expr1 ; subtract signs of operands in expr2 ; if expressions are same , vector must be 0. ; 

MAX_CHAR = 26


def adjSign(s, i):
    if (i == 0):
        return True
    if (s[i - 1] == '-'):
        return False
    return True


def eval(s, v, add):
    stk = []
    stk.append(True)
    i = 0

    while (i < len(s)):

        if (s[i] == '+' or s[i] == '-'):
            i += 1
            continue

        if (s[i] == '('):
            if (adjSign(s, i)):
                stk.append(stk[-1])
            else:
                stk.append(not stk[-1])
        elif (s[i] == ')'):
            stk.pop()
        else:
            if (stk[-1]):
                v[ord(s[i]) - ord('a')] += (1 if add else -
                                            1) if adjSign(s, i) else (-1 if add else 1)

            else:
                v[ord(s[i]) - ord('a')] += (-1 if add else 1) if adjSign(s,
                                                                         i) else (1 if add else -1)

        i += 1


def areSame(expr1, expr2):
    v = [0 for i in range(MAX_CHAR)]

    eval(expr1, v, True)
    eval(expr2, v, False)
    for i in range(MAX_CHAR):
        if (v[i] != 0):
            return False
    return True


if __name__ == '__main__':
    expr1 = "-(a+b+c)"
    expr2 = "-a-b-c"
    if (areSame(expr1, expr2)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# find index of closing bracket for a given opening bracket in an expression | python program to find index of closing bracket for a given opening bracket . ; function to find index of closing bracket for given opening bracket . ; if input is invalid . ; create a deque to use it as a stack . ; traverse through all elements starting from i . ; push all starting brackets ; pop a starting bracket for every closing bracket ; if deque becomes empty ; test function ; 

from collections import deque


def getIndex(s, i):
    if s[i] != '[':
        return -1
    d = deque()
    for k in range(i, len(s)):
        if s[k] == '[':
            d .append(s[i])
        elif s[k] == ']':
            d .popleft()
        if not d:
            return k
    return -1


def test(s, i):
    matching_index = getIndex(s, i)
    print(s + ", " + str(i) + ": " + str(matching_index))


def main():
    test("[ABC[23]][89]", 0)
    test("[ABC[23]][89]", 4)
    test("[ABC[23]][89]", 9)
    test("[ABC[23]][89]", 1)


if __name__ == "__main__":
    main()

# Expected output:
[ABC[23]][89], 0: 8
[ABC[23]][89], 4: 7
[ABC[23]][89], 9: 12
[ABC[23]][89], 1: -1
# find if an expression has duplicate parenthesis or not | function to find duplicate parenthesis in a balanced expression ; create a stack of characters ; iterate through the given expression ; if current character is close parenthesis ' ) ' ; pop character from the stack ; stores the number of characters between a closing and opening parenthesis if this count is less than or equal to 1 then the brackets are redundant else not ; push open parenthesis ' ( ' , operators and operands to stack ; no duplicates found ; 
def findDuplicateparenthesis(string):
    Stack = []
    for ch in string:
        if ch == ')':
            top = Stack .pop()
            elementsInside = 0
            while top != '(':
                elementsInside += 1
                top = Stack .pop()
            if elementsInside < 1:
                return True
        else:
            Stack .append(ch)
    return False


if __name__ == "__main__":
    string = "(((a+(b))+(c+d)))"
    if findDuplicateparenthesis(string):
        print("Duplicate Found")
    else:
        print("No Duplicates Found")

# Expected output:
Duplicate Found
# find next smaller of next greater in an array | function find next greater element ; create empty stack ; traverse all array elements in reverse order order == ' g ' we compute next greater elements of every element order == ' s ' we compute right smaller element of every element ; keep removing top element from s while the top element is smaller then or equal to arr [ i ] ( if key is g ) element is greater then or equal to arr [ i ] ( if order is s ) ; store the next greater element of current element ; if all elements in s were smaller than arr [ i ] ; push this element ; function to find right smaller element of next greater element ; stores indexes of next greater elements ; stores indexes of right smaller elements ; find next greater element here g indicate next greater element ; find right smaller element using same function nextgreater ( ) here s indicate right smaller elements ; if ng [ i ] = = - 1 then there is no smaller element on right side . we can find right smaller of next greater by arr [ rs [ ng [ i ] ] ] ; 
def nextGreater(arr, n, next, order):
    S = []
    for i in range(n - 1, -1, -1):
        while (S != [] and (arr[S[len(S) - 1]] <= arr[i]
               if (order == 'G')else arr[S[len(S) - 1]] >= arr[i])):
            S .pop()
        if (S != []):
            next[i] = S[len(S) - 1]
        else:
            next[i] = -1
        S .append(i)


def nextSmallerOfNextGreater(arr, n):
    NG = [None] * n
    RS = [None] * n
    nextGreater(arr, n, NG, 'G')
    nextGreater(arr, n, RS, 'S')
    for i in range(n):
        if (NG[i] != -1 and RS[NG[i]] != -1):
            print(arr[RS[NG[i]]], end=" ")
        else:
            print("-1", end=" ")


if __name__ == "__main__":
    arr = [5, 1, 9, 2, 5, 1, 7]
    n = len(arr)
    nextSmallerOfNextGreater(arr, n)

# Expected output:
2 2 -1 1 -1 -1 -1
# count natural numbers whose all permutation are greater than that number | return the count of the number having all permutation greater than or equal to the number . ; pushing 1 to 9 because all number from 1 to 9 have this property . ; take a number from stack and add a digit smaller than last digit of it . ; 
def countNumber(n):
    result = 0
    s = []
    for i in range(1, 10):
        if (i <= n):
            s .append(i)
            result += 1
        while len(s) != 0:
            tp = s[-1]
            s .pop()
            for j in range(tp % 10, 10):
                x = tp * 10 + j
                if (x <= n):
                    s .append(x)
                    result += 1
    return result


if __name__ == '__main__':
    n = 15
    print(countNumber(n))

# Expected output:
14
# delete consecutive same words in a sequence | function to find the size of manipulated sequence ; start traversing the sequence ; compare the current string with next one erase both if equal ; erase function delete the element and also shifts other element that 's why   i is not updated  ; update i , as to check from previous element again ; reduce sequence size ; increment i , if not equal ; return modified size ; 
def removeConsecutiveSame(v):
    n = len(v)
    i = 0
    while (i < n - 1):
        if ((i + 1) < len(v)) and (v[i] == v[i + 1]):
            v = v[:i]
            v = v[:i]
            if (i > 0):
                i -= 1
            n = n - 2
        else:
            i += 1
    return len(v[:i - 1])


if __name__ == '__main__':
    v = ["tom", "jerry", "jerry", "tom"]
    print(removeConsecutiveSame(v))

# Expected output:
0
# delete consecutive same words in a sequence | function to find the size of manipulated sequence ; start traversing the sequence ; push the current string if the stack is empty ; compare the current string with stack top if equal , pop the top ; otherwise push the current string ; return stack size ; 
def removeConsecutiveSame(v):
    st = []
    for i in range(len(v)):
        if (len(st) == 0):
            st .append(v[i])
        else:
            Str = st[-1]
            if (Str == v[i]):
                st .pop()
            else:
                st .append(v[i])
    return len(st)


if __name__ == '__main__':
    V = ["ab", "aa", "aa", "bcd", "ab"]
    print(removeConsecutiveSame(V))

# Expected output:
3
# decode a string recursively encoded as count followed by substring | returns decoded string for ' str ' ; traversing the string ; if number , convert it into number and push it into integerstack . ; if closing bracket ' ] ' , pop elemment until ' [ ' opening bracket is not found in the character stack . ; repeating the popped string ' temo ' count number of times . ; push it in the character stack . ; if ' [ ' opening bracket , push it into character stack . ; pop all the elmenet , make a string and return . ; 
def decode(Str):
    integerstack = []
    stringstack = []
    temp = ""
    result = ""
    i = 0
    while i < len(Str):
        count = 0
        if (Str[i] >= '0' and Str[i] <= '9'):
            while (Str[i] >= '0' and Str[i] <= '9'):
                count = count * 10 + ord(Str[i]) - ord('0')
                i += 1
            i -= 1
            integerstack .append(count)
        elif (Str[i] == ']'):
            temp = ""
            count = 0
            if (len(integerstack) != 0):
                count = integerstack[-1]
                integerstack .pop()
            while (len(stringstack) != 0 and stringstack[-1] != '['):
                temp = stringstack[-1] + temp
                stringstack .pop()
            if (len(stringstack) != 0 and stringstack[-1] == '['):
                stringstack .pop()
            for j in range(count):
                result = result + temp
            for j in range(len(result)):
                stringstack .append(result[j])
            result = ""
        elif (Str[i] == '['):
            if (Str[i - 1] >= '0' and Str[i - 1] <= '9'):
                stringstack .append(Str[i])
            else:
                stringstack .append(Str[i])
                integerstack .append(1)
        else:
            stringstack .append(Str[i])
        i += 1
    while len(stringstack) != 0:
        result = stringstack[-1] + result
        stringstack .pop()
    return result


if __name__ == '__main__':
    Str = "3[b2[ca]]"
    print(decode(Str))

# Expected output:
bcacabcacabcaca
# reverse a number using stack | stack to maintain order of digits ; function to push digits into stack ; function to reverse the number ; function call to push number 's   digits to stack ; popping the digits and forming the reversed number ; return the reversed number formed ; 

st = []


def push_digits(number):
    while (number != 0):
        st .append(number % 10)
        number = int(number / 10)


def reverse_number(number):
    push_digits(number)
    reverse = 0
    i = 1
    while (len(st) > 0):
        reverse = reverse + (st[len(st) - 1] * i)
        st .pop()
        i = i * 10
    return reverse


number = 39997
print(reverse_number(number))

# Expected output:
79993
# check if stack elements are pairwise consecutive | function to check if elements are pairwise consecutive in stack ; transfer elements of s to aux . ; traverse aux and see if elements are pairwise consecutive or not . we also need to make sure that original content is retained . ; fetch current top two elements of aux and check if they are consecutive . ; append the elements to original stack . ; 
def pairWiseConsecutive(s):
    aux = []
    while (len(s) != 0):
        aux .append(s[-1])
        s .pop()
    result = True
    while (len(aux) > 1):
        x = aux[-1]
        aux .pop()
        y = aux[-1]
        aux .pop()
        if (abs(x - y) != 1):
            result = False
        s .append(x)
        s .append(y)
    if (len(aux) == 1):
        s .append(aux[-1])
    return result


if __name__ == '__main__':
    s = []
    s .append(4)
    s .append(5)
    s .append(-2)
    s .append(-3)
    s .append(11)
    s .append(10)
    s .append(5)
    s .append(6)
    s .append(20)
    if (pairWiseConsecutive(s)):
        print("Yes")
    else:
        print("No")
    print("Stack content (from top)", "after function call")
    while (len(s) != 0):
        print(s[-1], end=" ")
        s .pop()

# Expected output:
Yes
Stack content (from top) after function call
20 6 5 10 11 -3 -2 5 4
# remove brackets from an algebraic string containing + and | function to simplify the string ; resultant string of max length equal to length of input string ; create empty stack ; if top is 1 , flip the operator ; if top is 0 , append the same operator ; x is opposite to the top of stack ; append value equal to top of the stack ; if closing parentheses pop the stack once ; copy the character to the result ; 
def simplify(Str):
    Len = len(Str)
    res = [None] * Len
    index = 0
    i = 0
    s = []
    s .append(0)
    while (i < Len):
        if (Str[i] == '+'):
            if (s[-1] == 1):
                res[index] = '-'
                index += 1
            if (s[-1] == 0):
                res[index] = '+'
                index += 1
        elif (Str[i] == '-'):
            if (s[-1] == 1):
                res[index] = '+'
                index += 1
            elif (s[-1] == 0):
                res[index] = '-'
                index += 1
        elif (Str[i] == '(' and i > 0):
            if (Str[i - 1] == '-'):
                x = 0 if (s[-1] == 1)else 1
                s .append(x)
            elif (Str[i - 1] == '+'):
                s .append(s[-1])
        elif (Str[i] == ')'):
            s .pop()
        else:
            res[index] = Str[i]
            index += 1
        i += 1
    return res


if __name__ == '__main__':
    s1 = "a-(b+c)"
    s2 = "a-(b-c-(d+e))-f"
    r1 = simplify(s1)
    for i in r1:
        if i is not None:
            print(i, end=" ")
        else:
            break
    print()
    r2 = simplify(s2)
    for i in r2:
        if i is not None:
            print(i, end=" ")
        else:
            break

# Expected output:
a - b - c 
a - b + c + d + e - f
# heapsort | to heapify subtree rooted at index i . n is size of heap ; initialize largest as root ; left = 2 * i + 1 ; right = 2 * i + 2 ; see if left child of root exists and is greater than root ; see if right child of root exists and is greater than root ; change root , if needed ; heapify the root . ; the main function to sort an array of given size ; build a maxheap . ; one by one extract elements ; swap ; call max heapify on the reduced heap ; 
def heapify(arr, n, i):
    largest = i
    l = 2 * i + 1
    r = 2 * i + 2
    if l < n and arr[largest] < arr[l]:
        largest = l
    if r < n and arr[largest] < arr[r]:
        largest = r
    if largest != i:
        arr[i], arr[largest] = arr[largest], arr[i]
        heapify(arr, n, largest)


def heapSort(arr):
    n = len(arr)
    for i in range(n // 2 - 1, -1, -1):
        heapify(arr, n, i)
    for i in range(n - 1, 0, -1):
        arr[i], arr[0] = arr[0], arr[i]
        heapify(arr, i, 0)


arr = [12, 11, 13, 5, 6, 7]
heapSort(arr)
n = len(arr)
print("Sorted array is")
for i in range(n):
    print("%d" % arr[i]),

# Expected output:
Sorted array is
5
6
7
11
12
13
# iterative heapsort | function build max heap where value of each child is always smaller than value of their parent ; if child is bigger than parent ; swap child and parent until parent is smaller ; swap value of first indexed with last indexed ; maintaining heap property after each swapping ; if left child is smaller than right child point index variable to right child ; if parent is smaller than child then swapping parent with child having higher value ; 
def buildMaxHeap(arr, n):
    for i in range(n):
        if arr[i] > arr[int((i - 1) / 2)]:
            j = i
            while arr[j] > arr[int((j - 1) / 2)]:
                (arr[j], arr[int((j - 1) / 2)]
                 ) = (arr[int((j - 1) / 2)], arr[j])
                j = int((j - 1) / 2)


def heapSort(arr, n):
    buildMaxHeap(arr, n)
    for i in range(n - 1, 0, -1):
        arr[0], arr[i] = arr[i], arr[0]
        j, index = 0, 0
        while True:
            index = 2 * j + 1
            if (index < (i - 1) and arr[index] < arr[index + 1]):
                index += 1
            if index < i and arr[j] < arr[index]:
                arr[j], arr[index] = arr[index], arr[j]
            j = index
            if index >= i:
                break


if __name__ == '__main__':
    arr = [10, 20, 15, 17, 9, 21]
    n = len(arr)
    print("Given array: ")
    for i in range(n):
        print(arr[i], end=" ")
    print()
    heapSort(arr, n)
    print("Sorted array: ")
    for i in range(n):
        print(arr[i], end=" ")

# Expected output:
Given array: 
10 20 15 17 9 21 
Sorted array: 
9 10 15 17 20 21
# how to check if a given array represents a binary heap ? | returns true if arr [ i . . n - 1 ] represents a max - heap ; if a leaf node ; if an internal node and is greater than its children , and same is recursively true for the children ; 
def isHeap(arr, i, n):
    if i >= int((n - 2) / 2):
        return True
    if (arr[i] >= arr[2 * i + 1] and arr[i] >= arr[2 * i + 2]
            and isHeap(arr, 2 * i + 1, n) and isHeap(arr, 2 * i + 2, n)):
        return True
    return False


if __name__ == '__main__':
    arr = [90, 15, 10, 7, 12, 2, 7, 3]
    n = len(arr) - 1
    if isHeap(arr, 0, n):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# how to check if a given array represents a binary heap ? | returns true if arr [ i . . n - 1 ] represents a max - heap ; start from root and go till the last internal node ; if left child is greater , return false ; if right child is greater , return false ; 
def isHeap(arr, n):
    for i in range(int((n - 2) / 2) + 1):
        if arr[2 * i + 1] > arr[i]:
            return False
        if (2 * i + 2 < n and arr[2 * i + 2] > arr[i]):
            return False
    return True


if __name__ == '__main__':
    arr = [90, 15, 10, 7, 12, 2, 7, 3]
    n = len(arr)
    if isHeap(arr, n):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# connect n ropes with minimum cost | python3 program to connect n ropes with minimum cost ; create a priority queue out of the given list ; initializ result ; while size of priority queue is more than 1 ; extract shortest two ropes from arr ; connect the ropes : update result and insert the new rope to arr ; 

import heapq


def minCost(arr, n):
    heapq .heapify(arr)
    res = 0
    while (len(arr) > 1):
        first = heapq .heappop(arr)
        second = heapq .heappop(arr)
        res += first + second
        heapq .heappush(arr, first + second)
    return res


if __name__ == '__main__':
    lengths = [4, 3, 2, 6]
    size = len(lengths)
    print("Total cost for connecting ropes is " + str(minCost(lengths, size)))

# Expected output:
Total cost for connecting ropes is 29
# smallest derangement of sequence | python3 program to generate smallest derangement using priority queue . ; generate sequence and insert into a priority queue . ; generate least derangement ; print derangement ; 
def generate_derangement(N):
    S = [i for i in range(N + 1)]
    PQ = []
    for i in range(1, N + 1):
        PQ .append(S[i])
    D = [0] * (N + 1)
    PQ .sort()
    for i in range(1, N + 1):
        PQ .sort()
        d = PQ[0]
        del PQ[0]
        if (d != S[i]) or (i == N):
            D[i] = d
        else:
            PQ .sort()
            D[i] = PQ[0]
            del PQ[0]
            PQ .append(d)
    if D[N] == S[N]:
        t = D[N - 1]
        D[N - 1] = D[N]
        D[N] = t
    for i in range(1, N + 1):
        print(D[i], end=" ")
    print()


generate_derangement(10)

# Expected output:
2 1 4 3 6 5 8 7 10 9
# smallest derangement of sequence | efficient python3 program to find smallest derangement . ; generate sequence s ; generate derangement ; only if i is odd swap s [ n - 1 ] and s [ n ] ; print derangement ; 
def generate_derangement(N):
    S = [0] * (N + 1)
    for i in range(1, N + 1):
        S[i] = i
    D = [0] * (N + 1)
    for i in range(1, N + 1, 2):
        if i == N:
            D[N] = S[N - 1]
            D[N - 1] = S[N]
        else:
            D[i] = i + 1
            D[i + 1] = i
    for i in range(1, N + 1):
        print(D[i], end=" ")
    print()


if __name__ == '__main__':
    generate_derangement(10)

# Expected output:
2 1 4 3 6 5 8 7 10 9
# largest derangement of a sequence | python3 program to find the largest derangement ; stores result ; insert all elements into a priority queue ; fill up res [ ] from left to right ; new element poped equals the element in original sequence . get the next largest element ; if given sequence is in descending order then we need to swap last two elements again ; 
def printLargest(seq, N):
    res = [0] * N
    pq = []
    for i in range(N):
        pq .append(seq[i])
    for i in range(N):
        pq .sort()
        pq .reverse()
        d = pq[0]
        del pq[0]
        if (d != seq[i] or i == N - 1):
            res[i] = d
        else:
            res[i] = pq[0]
            del pq[0]
            pq .append(d)
    if (res[N - 1] == seq[N - 1]):
        res[N - 1] = res[N - 2]
        res[N - 2] = seq[N - 1]
    print("Largest Derangement")
    for i in range(N):
        print(res[i], end=" ")


seq = [92, 3, 52, 13, 2, 31, 1]
n = len(seq)
printLargest(seq, n)

# Expected output:
Largest Derangement
52 92 31 3 13 1 2
# find the next perfect square greater than a given number | python3 implementation of above approach ; function to find the next perfect square ; 

import math


def nextPerfectSquare(N):
    nextN = math .floor(math .sqrt(N)) + 1
    return nextN * nextN


if __name__ == '__main__':
    N = 35
    print(nextPerfectSquare(N))

# Expected output:
36
# print all substring of a number without any conversion | python3 implementation of above approach ; function to print the substrings of a number ; calculate the total number of digits ; 0.5 has been added because of it will return double value like 99.556 ; print all the numbers from starting position ; update the no . ; update the no . of digits ; 

import math


def printSubstrings(n):
    s = int(math .log10(n))
    d = (math .pow(10, s))
    k = d
    while (n > 0):
        while (d > 0):
            print(int(n // d))
            d = int(d / 10)
        n = int(n % k)
        k = int(k // 10)
        d = k


if __name__ == '__main__':
    n = 123
    printSubstrings(n)

# Expected output:
1
12
123
2
23
3
# Modulo power for large numbers represented as strings | Python3 program to find ( a ^ b ) % MOD where a and b may be very large and represented as strings . ; Returns modulo exponentiation for two numbers represented as long long int . It is used by powerStrings ( ) . Its complexity is log ( n ) ; Returns modulo exponentiation for two numbers represented as strings . It is used by powerStrings ( ) ; We convert strings to number ; calculating a % MOD ; calculating b % ( MOD - 1 ) ; Now a and b are long long int . We calculate a ^ b using modulo exponentiation ; As numbers are very large that is it may contains upto 10 ^ 6 digits . So , we use string .

MOD = 1000000007


def powerLL(x, n):
    result = 1
    while (n):
        if (n & 1):
            result = result * x % MOD
        n = int(n / 2)
        x = x * x % MOD
    return result


def powerStrings(sa, sb):
    a = 0
    b = 0
    for i in range(len(sa)):
        a = (a * 10 + (ord(sa[i]) - ord('0'))) % MOD
    for i in range(len(sb)):
        b = (b * 10 + (ord(sb[i]) - ord('0'))) % (MOD - 1)
    return powerLL(a, b)


sa = "2"
sb = "3"
print(powerStrings(sa, sb))

# Expected output:
8