I have a class containing:
class CounterList:
__n_comparisons__ = 0
def __init__(self, data=None):
if data is None:
self.data = []
else:
self.data = data
self.__n_accesses__ = 0
def __getitem__(self, i):
self.__n_accesses__ += 1
return self.data[i]
def __setitem__(self, i, item):
self.__n_accesses__ += 1
if type(item) != CounterNode:
raise ValueError("Only Counter objects can be placed in a CounterList")
else:
self.data[i] = item
def __delitem__(self, key):
self.__n_accesses__ += 1
del(self.data[key])
def __len__(self):
return len(self.data)
def __repr__(self):
return repr(self.data)
def __contains__(self, item):
raise TypeError("You can't use the 'in' keyword with a CounterList")
def __eq__(self, other):
self.__n_comparisons__ += 1
return self.data == other
def insert(self, index, item):
if type(item) != CounterNode:
raise ValueError("Only Counter objects can be added to a CounterList")
else:
self.data.insert(index, item)
def index(self, a=None):
raise TypeError("You can't do that with a CounterList")
def append(self, item):
if type(item) != CounterNode:
raise ValueError("Only Counter objects can be added to a CounterList")
else:
self.data.append(item)
def get_accesses(self):
return self.__n_accesses__
@classmethod
def get_comparisons(cls):
return cls.__n_comparisons__
@classmethod
def reset_comparisons(cls):
cls.__n_comparisons__ = 0
and using it I need to, using a list, return a 'counterlist' containing all the strings in the original list plus the number of times the string appears in the list.
e.g.
original_list = ["hello", "hi", "hi"]
CounterList = ["hello", 1, "hi", 2]
I am a little lost, but have made a start on a while loop that will check the original list against the new list and if the string is not there, then will add it to the new list, and increase a counter by one, then it will delete the first item in the original list until that list is empty before finally displaying the result.
I am fairly lost however, and any guidence will be much appreciated, as I am sure there must be an easier way to do this.
Thank you
from classes_1 import CounterList
def word_counter_seq(words_list):
counter = 0
new_list = []
while words_list != False:
if words_list[0].__eq__(new_list):
counter += 1
words_list[0].append[new_list]
words_list[0].__delitem__()
else:
counter+=1
words_list[0].__delitem__()
print (counter)
print (new_list)
a_list = ["hello", "hi", "hi"]
(word_counter_seq(a_list))