Let i have the following class in python:
class Word:
def __init__(self, _lemma, _frequency):
self.lemma = str(_lemma)
self.frequency = int(_frequency)
now i want to create a collection of class Word which hold following logic when an Word object word1 is being added to collection:
- if the collection contains a
Wordobjectwordwhereword.lemma = word1.lemmathenword.frequency = word.frequency + word1.frequency - else add
word1to collection
How can i do it?
Previously i used a list to do so where i checked if the list contains a Word object which has same lemma as word1.lemma. But the approach has O(n^2) complexity to add n word in the collection.
from Word import Word
class Corpus:
def __init__(self, _name, _total_count):
self.name = str(_name)
self.total_count = int(_total_count)
self.words = []
def add(self, _word):
find_word = [index for index, word in enumerate(self.words) if word.lemma == _word.lemma] # O(n)
if len(find_word) == 0:
self.words.append(Word(_word.lemma, _word.frequency))
else:
self.words[find_word[0]].frequency = self.words[find_word[0]].frequency + _word.frequency