有人可以告诉我为什么我的添加功能不起作用: (它只添加第一个{'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
答案 0 :(得分:2)
问题是,在第一个循环current
始终为None
之后,即使在found is False
的情况下也不会执行第二个循环体。
答案 1 :(得分:0)
答案 2 :(得分:0)
现在是学习如何使用Python调试器的最佳时机!如果你使用它,你可以学到很多东西。编写失败的测试脚本并使用python -m pdb testscript.py
启动调试器。 Doug Hellmann写了关于python模块的好文章,你应该read the one about the pdb module。