2011-09-13 18 views
0

あなたは私を助けてください、私はリンク機能を使ってリンクリストをソートしようとしていますが、エラーメッセージが表示されます: f.add 'b'、2) Attribute: 'NoneType'オブジェクトに 'next'属性がありません どうすればこの問題を回避できますか? ありがとうございます。 current.next == Noneあれば何が起こるかリンクリストを降順でソートしようとしています

ラインで
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 


これを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}) 

あなたは、私はエラーがoccuringが、これを修正する方法イムわからされていないのthatsを考える

x.most_common() 
+0

を使用してデータのソート済みキーと値のペアの表現を回復することができます。私は次のようなステートメントを持っていますか?next1がNoneの場合:現在のものを最後のものにします。どのように私はこれを実装するのですか? – Nirali

+0

@Nirali:まず、擬似コードで何をしたいかを考えてください。四角形と矢印付きの図は、この種のポインタ操作を手助けします。 (例えば、リストの最後にヒットした場合、 'current.next == None'、' current.next == Frequency(letter、frequency) 'を作成します。 – katrielalex

関連する問題