2011-09-13 75 views
0

你能幫我,我想根據添加功能的文檔排序鏈接列表,但我得到一個錯誤,說: f.add( 'b',2) 文件「」,第69行,加上 AttributeError:'NoneType'對象沒有'next'屬性 我該如何避免這種情況? 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 
     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) 

回答

2

在行

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() 
+0

我認爲,多數民衆贊成在錯誤的現象發生,但林不知道如何糾正這一點。 。我是否應該有這樣的陳述:如果next1是None:使當前的一個是最後一個。我如何實現這個? – Nirali

+0

@Nirali:首先制定你想要在僞代碼中做什麼。帶正方形和箭頭的圖表幫助我制定出這種指針操作。 (例如,如果我們擊中了列表的末尾,那麼'current.next == None',使'current.next ==頻率(字母,頻率)'。) – katrielalex