I am trying to run this test on my add function for my linked list:
>>> test = FrequencyList()
>>> test.add('a', 3)
>>> test
Frequency List -> Frequency('a', 3) -> None
>>> test.add('b', 2)
>>> test
Frequency List -> Frequency('a', 3) -> Frequency('b', 2) -> None
But my output is just Frequency List -> None
with the error: File "x-wingide-python-shell://130365360/2", line 75, in add - TypeError: init() takes 1 positional argument but 3 were given
Amanda_CAmanda_C
2 Answers 2
You need to change FrequencyList by Frequency, but you also have to add it correctly. This example could work:
class FrequencyList(object):
"""Stores a collection of Frequency objects as a linked list."""
def __init__(self):
""" Creates an empty FrequencyList """
self.head = None
self.last = None
def add(self, letter, frequency=1):
temp = Frequency(letter, frequency)
if self.head is None:
self.head = temp
self.last = temp
else:
self.last.next_node = temp
self.last = temp
def __repr__(self):
if self.head is not None:
next_freq = self.head
data = "Frequency List -> "
while next_freq is not None:
data += repr(next_freq) + " -> "
next_freq = next_freq.next_node
data += "None"
return data
else:
return "Empty List"
class Frequency(object):
"""
Stores a letter:frequency pair.
"""
def __init__(self, letter, frequency):
self.letter = letter
self.frequency = frequency
# The next Frequency object when stored as part of a linked list
self.next_node = None
def __repr__(self):
return 'Frequency({}, {})'.format(repr(self.letter), repr(self.frequency))
test = FrequencyList()
test.add('a', 3)
print(test)
test.add('b', 2)
print(test)
answered Jan 9, 2021 at 23:56
If add means is adding node to a list, the solution is to replace temp = FrequencyList(letter, frequency)
with temp = Frequency(letter, frequency)
.
answered Jan 9, 2021 at 23:43
lang-py