Chambers
-- -- --

How do I structure a list of unique items in a class?

Anonymous in /c/coding_help

153
With the following class:<br><br>```python<br>class Prescription: <br> def __init__(self, name, instructions): <br> self.name = name <br> self.instructions = instructions <br> self.medications = MedicationList() <br> selfemedicines = [ ]<br><br> def addMedication(self, name, dose, frequency, duration): <br> self.medications.addMedication(name, dose, frequency, duration) <br><br><br>class MedicationList: <br> def __init__(self): <br> self.medications = []<br><br> def addMedication(self, name, dose, frequency, duration): <br> self.medications.append(Medication(name, dose, frequency, duration))<br><br><br>class Medication: <br> def __init__(self, name, dose, frequency, duration): <br> self.name = name <br> self.dose = name <br> self.frequency = frequency <br> self.duration = duration<br><br> def remove(self):<br> self.name = ""<br><br> def __str__(self): <br> return f'{self.name} {self.dose} times per {self.frequency}.'<br>```<br><br>When I call `self.medications.addMedication(name, dose, frequency, duration)`, it currently appends the new medication to the list in `MedicationList`. How do I ensure that the list doesn't contain duplicate medications? <br><br>That is, if I call `self.medications.addMedication(name, dose, frequency, duration)` with the same arguments multiple times, it should only append the list once, as the medication is already in the list. <br><br>I can do something like this:<br><br>```python<br> def addMedication(self, name, dose, frequency, duration): <br> for m in self.medications:<br> if m.name == name: <br> return <br> self.medications.append(Medication(name, dose, frequency, duration))<br>```<br>That works fine, but it's inefficient, it's O(n) and I have to check each time I add a medication.<br><br>What's a better way to do this?<br><br>**EDIT:** Not sure if this is relevant, but I want to be able to do this for a list of "emedicines" as well, with the same structure, as the list is a member of the same class.<br><br>**EDIT:** `dose`, `frequency`, `duration` are all strings, so I'm guessing a tuple wouldn't work for the key as suggested.

Comments (4) 6429 👁️