Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

adding an element to a linked list python

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

question from:https://stackoverflow.com/questions/65648716/adding-an-element-to-a-linked-list-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...