question archive Emulate the stack behaviour using the list data structure
Subject:Computer SciencePrice:5.86 Bought12
Emulate the stack behaviour using the list data structure.
a) Complete the methods of the following Stack class according to their description
In [ ]:
class Stack: def __init__(self): """ Initialize a new stack """ self.elements = [] def push(self, new_item): """ Append the new item to the stack """ ## CODE HERE ### def pop(self): """ Remove and return the last item from the stack """ ## CODE HERE ### def size(self): """ Return the total number of elements in the stack """ ## CODE HERE ### def is_empty(self): """ Return True if the stack is empty and False if it is not empty """ ## CODE HERE ### def peek(self): """ Return the element at the top of the stack or return None if the stack is empty """ ## CODE HERE ###
b) Use the Stack class that you defined in Q3a to complete the code of the is_valid() function, which checks whether the order of the brackets of an arithmetic expression is correct. Some examples are given below:
In [18]:
exp1 = "(2+3)+(1-5)" # True exp2 = "((3*2))*(7/3))" # False exp3 = "(3*5))]" # False
In [17]:
def is_valid(exp): """ Check the order of the brackets Returns True or False """ opening = ['(', '[', '{'] closing = [')', ']', '}'] ## CODE HERE ## return ## CODE HERE ## is_valid(exp1) is_valid(exp2) is_valid(exp3)
c) Use the Stack class that you defined in Q3a to complete the code of the count_pairs() function, which returns the number of the valid bracket pairs of an arithmetic expression. Some examples are given below:
In [13]:
exp1 = "(2+3)+(1-5)" # 2 pairs exp2 = "((([()])))" # 5 pairs exp3 = "[([])" # 2 pairs
In [12]:
def count_pairs(exp): """ Count the valid number of brackets Returns the total number of valid brackets in the string """ opening = ['(', '[', '{'] closing = [')', ']', '}'] ## CODE HERE ## return ## CODE HERE ## count_pairs(exp1) count_pairs(exp2) count_pairs(exp3)
Purchased 12 times