添加到链接列表

时间:2011-09-17 09:59:11

标签: python

有人可以告诉我为什么我的添加功能不起作用: (它只添加第一个{'a',3}而不是其余的) 三江源

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

3 个答案:

答案 0 :(得分:2)

问题是,在第一个循环current始终为None之后,即使在found is False的情况下也不会执行第二个循环体。

答案 1 :(得分:0)

在我看来,还有另一个问题。 当发现是假和current.frequency&gt;频率,你应该将current.next.next设置为上一个, 就像是 :     temp = current.next     current.next =频率(     current.next.next =温度

答案 2 :(得分:0)

现在是学习如何使用Python调试器的最佳时机!如果你使用它,你可以学到很多东西。编写失败的测试脚本并使用python -m pdb testscript.py启动调试器。 Doug Hellmann写了关于python模块的好文章,你应该read the one about the pdb module