Wednesday, May 13, 2020

Print Bracket Number using stack

Given an expression exp of length n consisting of some brackets. The task is to print the bracket numbers when the expression is being parsed.

Input:
The first line contains an integer T, the number of test cases. For each test case, there is a string exp containing the expression.

Output:
For each test case, the output is the bracket numbers of the expression.
Example:
Input:

3​
(a+(b*c))+(d/e)​
((())(()))
((((()
Output:
1 2 2 1 3 3
1 2 3 3 2 4 5 5 4 1
1 2 3 4 5 5


#code
t= int(input())
while(t>0):
    #n=int(input())
    a= str(input())
    from queue import LifoQueue
    stack = LifoQueue(maxsize = len(a))
    j = 0
    k = 0
    l = ""
    for i in range(len(a)):
        if a[i] == '(':
            j = j + 1
            stack.put(j)
            l = l + str(j)+ " "
        if a[i] == ')':
            k = stack.get()
            l = l + str(k) + " "
    print(l)
    t -= 1

Sunday, May 10, 2020

Find the smallest sum of the two numbers formed using a list of numbers

Q. Find the smallest sum of the two numbers formed using a list of numbers, such that each number of the list is used to form the two numbers.
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. First line of each test case contains an integer N denoting the size of the array. Next line of each test contains N space seperated integers denoting the elements of the array.

Solution:
The answer is the sum of the two smallest numbers that can be formed using a list of numbers.
To construct the smallest two numbers, first we sort the given list in ascending order.
Then we take alternate digits from the list and form the two numbers. Finally we add the two to get the answer.

# Solution in Python
t= int(input())
while(t>0):
    n=int(input())
    a=list(map(int,input().split()))
    a.sort()
    q1=[]
    q2=[]
    n1= 0
    n2= 0
    for i in range(len(a)):
        if(i%2==0):
            q1.append(a[i])
        else:
            q2.append(a[i])
    for j in reversed(range(len(q1))):
        n1 = n1 + q1.pop(0)*10**(j)
    for k in reversed(range(len(q2))):
        n2 = n2 + q2.pop(0)*10**(k)
    print(n1+n2)
    t -= 1


Queue in Python https://www.geeksforgeeks.org/queue-in-python/

Print a range in reversed order

This can be done as:






                                

Sacred Thought

28 April 2024 Today I am going to explain verse 31 - 38 chapter two for you all. There is no opportunity better than a righteous war (सत्य औ...