我正在尝试将链表按降序排序
请问你能帮我吗?我正在尝试按照文档中的说明来排序链表,但我遇到了一个错误,错误信息是:
f.add('b', 2)
文件 "", 第 69 行,在 add 函数中
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)
1 个回答
2
在这些代码行中
current = current.next
next1 = current.next
如果 current.next == None
会发生什么呢?
我不确定你是在做Python练习,还是因为你真的需要这个功能;如果是后者,其实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()