In this task, you are required to define a class for analysing the number of occ
ID: 3720113 • Letter: I
Question
In this task, you are required to define a class for analysing the number of occurrences for each of the letters (i.e. ‘A’ to ‘Z) and numerals (i.e. ‘0’ to ‘9’) from the decoded sequences. This class should have one instance variable which is a dictionary structure that is used for keeping track of the number of occurrences for each of the letters and numerals decoded by the Morse Code decoder in Task 1.
The implementation of this character analyser class should include the following three methods:
• __init__(self):
This is the constructor that is required for creating instances of this class. You should
define and initialise the dictionary structure for characters (i.e. the instance variable) in the constructor.
• __str__(self):
Re-define this method to present the number of occurrences for each of the letters and numerals in a readable format. You should return a formatted string in this method.
Explanation / Answer
I have used python 3.6 version.
The decoded sequence is considered as a list of characters.
Python3.6 Code
#!/usr/bin/python3.6
class analyser():
def __init__(self):
"Intialization function"
self._charDict = {} ##instance variable intialized as dictionary.
def __str__(self):
Str = ""
for Char, Count in self._charDict.items():
Str = Str + "char '{0}' --- {1} ".format(Char, Count)
return Str
def analyse_characters(self, decoded_sequence):
"This function update the charachter count into the dictionary from the given list of chaaracters"
for Char in decoded_sequence:
if Char not in self._charDict:
self._charDict[Char] = 1
else :
self._charDict[Char] += 1
Anal = analyser()
Anal.analyse_characters(['a', 'b', 'a'])
print(Anal),
--------------------------------------------
Output shown after running this program :
$)python main.py
char 'a' --- 2
char 'b' --- 1
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.