开发者

Adding to a linked list

Can someone please tell me why my add function is not working: (it only adds the first {'a', 3} but not the rest) thankyou

class Frequency(object):
    """
    Stores a letter:frequency pair.

    >>> f = Frequency('c', 2)
    >>> f.letter
    'c'
    >>> f.frequency
    2
    >>> f
    {c: 2}
    """
    def __init__(self, letter, frequency):
        self.letter = letter
        self.frequency = frequency
        self.next = None

    def __repr__(self):
        return '{%s: %d}' % (self.letter, self.frequency)

class SortedFrequencyList(object):
    """
    Stores a collection of Frequency objects as a sorted linked list.
    Items are sorted from the highest frequency to the lowest.
    """
    def __init__(self):
        self.head = None

    def add(self, letter, frequency):
        """
        Adds the given `letter`:`frequency` combination as a Frequency object
        to the list. If the given `letter` is already in the list, the given
        `frequency` is added to its frequency.

        >>> f = SortedFrequencyList()
        >>> f.add('开发者_开发问答a', 3)
        >>> f
        ({a: 3})
        >>> f.add('b', 2)
        >>> f
        ({a: 3}, {b: 2})
        >>> f.add('c', 4)
        >>> f
        ({c: 4}, {a: 3}, {b: 2})
        >>> f.add('b', 3)
        >>> f
        ({b: 5}, {c: 4}, {a: 3})
        """

        current = self.head
        found = False
        prev = None

        if self.head is None:
            self.head = Frequency(letter, frequency)
        else:
            while current is not None:
                if current.letter == letter:
                    current.frequency = current.frequency + frequency
                    found = True
                prev = current
                current = current.next


            if found is False:
                while current is not None:
                    if current.frequency > frequency:
                        current.next = Frequency(letter, frequency)

                    elif current.frequency < frequency:
                        temp = prev
                        prev = Frequency(letter, frequency)
                        current = temp

                    prev = current
                    current = current.next


The problem is that after the first loop current is always None, therefore the second loop body is never executed even in case found is False.


it seems to me that there is another issue. when found is false and current.frequency > frequency, you should set current.next.next to the previous next, something like : temp = current.next current.next=Frequency( current.next.next=temp


This is the right time to learn how to use the Python debugger ! You can learn a lot if you use it. Write a testscript which fails and start the debugger with python -m pdb testscript.py. Doug Hellmann writes nice articles about python modules, you should read the one about the pdb module.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜