繁体   English   中英

我试图按降序对链表进行排序

[英]I am trying to sort a linked list in descending order

你可以请帮助我,我试图根据add函数中的文档对链表进行排序但是我收到的错误是:f.add('b',2)File“”,第69行,另外AttributeError:'NoneType'对象没有属性'next'我怎么能避免这种情况? 谢谢。

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
        if self.head is None:
            self.head = Frequency(letter, frequency)
        else:
            prev = None
            while current is not None:
                if current.letter == letter:
                    current.frequency = current.frequency + frequency
                    found = True
                prev = current
                current = current.next

                next1 = current.next
                if next1 is None:
                    current = next1

                if current.frequency < next1.frequency:
                    temp = current
                    current = next1
                    next1 = temp
                else:
                    current = next1
                    next1 = current.next.next


            if found is False:
                prev.next = Frequency(letter, frequency)

在线

current = current.next
next1 = current.next

如果current.next == None会发生什么?


我不知道你是在做这个Python练习还是因为你真的需要这个功能; 如果是后者,已经有一个内置的类为你做这个。 它是collections.Counter (在Python 2.7或3.x中); 如果你使用的是早期版本,那么你可以通过继承collections.defaultdict自己制作一个版本。 它还使用Python字典而不是将数据存储为键值对。

例:

>>> from collections import Counter
>>> x = Counter()
>>> x['a'] += 2
>>> x['b'] += 3
>>> x['c'] += 1
>>> x
Counter({'b': 3, 'a': 2, 'c': 1})

您可以使用恢复数据的已排序键值对表示

x.most_common()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM