question archive Question 1: Emulate the stack behaviour using the list data structure
Subject:Computer SciencePrice:3.86 Bought7
Question 1:
Emulate the stack behaviour using the list data structure.
a) Complete the methods of the following Stack class according to their description
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:
exp1 = "(2+3)+(1-5)" # True exp2 = "((3*2))*(7/3))" # False exp3 = "(3*5))]" # False
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:
exp1 = "(2+3)+(1-5)" # 2 pairs exp2 = "((([()])))" # 5 pairs exp3 = "[([])" # 2 pairs
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)
Question 2:
According to each method's documentation, complete the code of the TextProcessor class and its subclass TextAnalyzer.
class TextProcessor: def __init__(self, text): self.text = text def setStopWords(): ''' set stop words as recieved in the parameters ''' ## CODE HERE ## def getStopWords(): ''' return stop words ''' ## CODE HERE ## def getUniqWords(self): return set(self.__text.split()) def getFilteredText(self): ''' remove filter words from the text return filtered text ''' ## CODE HERE ## class TextAnalyzer: def __init__(): ''' Construct the class ''' ## CODE HERE ## def getWordFrequency(): ''' Call the getFilteredText() method Create a dictionary of words key = word and value= frequency return the dictionary ''' ## CODE HERE ##
Verify the correctness of your code using the following steps:
ta = TextAnalyzer("a quick brown fox " +
"a quick brown fox jumps " +
"a quick brown fox jumps over " +
"a quick brown fox jumps over the " +
"a quick brown fox jumps over the lazy " +
"a quick brown fox jumps over the lazy dog")
2.Assign a list of stop words using the setStopWords() method: ta.setStopWords(['a', 'the'])
3.Count the occurrences of each word using the getWordFrequency() method: ta.getWordFrequency()
4.The output should be as follows {'quick': 6, 'brown': 6, 'fox': 6, 'jumps': 5, 'over': 4, 'lazy': 2, 'dog': 1}}
(ONLY QUESTION 2 is required to answer)

Below is one of the ways how problem 2 can be solved
class TextProcessor:
def __init__(self, text):
self.__text = text
self.__stop_words = []
def setStopWords(self, stop_words):
self.__stop_words = stop_words
def getStopWords(self):
return self.__stop_words
def getUniqWords(self):
return set(self.__text.split())
def getFilteredText(self,filter_words):
# first get the words from the text
words = self.__text.split()
new_text = ""
# now iterate on words and if we find that word is not in filter_words list we
# we add that word to new text
for word in words:
if word not in filter_words:
new_text = new_text + " " + word
# in case if there are spaces around the new text we remove that
new_text.strip()
return new_text
class TextAnalyzer(TextProcessor):
def __init__(self, text):
TextProcessor.__init__(self, text)
def getWordFrequency(self):
# create a dictionary
freq_dict = dict()
# first remove the stopwords from the text
filtered_text = self.getFilteredText(self.getStopWords())
# now create a list of words in filtered text
filtered_words = filtered_text.split()
# now iterate on words of the new text and if we find that this word
# is not in dictionary then we add this word as key and its frequency as 1
# otherwise we increment the count of this key by 1
for word in filtered_words:
if word not in freq_dict.keys():
freq_dict[word] = 1
else:
freq_dict[word] = freq_dict[word] + 1
return freq_dict
if __name__ == "__main__":
# create an instance of TextAnalyzer class
ta = TextAnalyzer("a quick brown fox " + "a quick brown fox jumps " + "a quick brown fox jumps over " + "a quick brown fox jumps over the " + "a quick brown fox jumps over the lazy " + "a quick brown fox jumps over the lazy dog")
# set the stopwords
ta.setStopWords(['a', 'the'])
# now get the frequency of words and print that
freq_dict = ta.getWordFrequency()
print(freq_dict)
output:
{'quick': 6, 'brown': 6, 'fox': 6, 'jumps': 5, 'over': 4, 'lazy': 2, 'dog': 1}

