通过查看作业和实践,我们使用了链表,并获得了以下代码:
`
class LinkedList:
class ListNode:
def __init__(self, data=None):
self.next = None
self.prev = None
self.data = data
def __init__(self):
self.first = None
self.last = None
self.count = 0
self.char_count = 0
def append(self, data):
n = LinkedList.ListNode(data)
if self.first is None: # Special case for empty lists
self.first = n
self.last = n
else: # Add the node to the end.
n.prev = self.last # the old .last becomes the new nodes previous
self.last.next = n # the old .last needs it's next to point to thenew node
self.last = n # point the .last node to be the new node.
self.count += 1
def size(self):
return self.count
def iter(self):
curr = self.first
while curr:
ret = curr.data
curr = curr.next
yield ret
def delete(self, data):
curr = self.first
deleted_fl = False
if curr is None: # LIST IS EMPTY, TRIVIAL CASE
deleted_fl = False
elif curr.data == data: # REMOVE FROM FRONT
if self.first == self.last: # IF REMOVING THE FIRST AND ONLY NODE
self.last = None
self.first = curr.next
deleted_fl = True
elif self.last.data == data: #REMOVE FROM END
self.last = self.last.prev
self.last.next = None
deleted_fl = True
else: # SEARCH THE REST TO SEE IF IT MATCHES
while curr:
if curr.data == data:
curr.prev.next = curr.next
curr.next.prev = curr.prev
deleted_fl = True
break
curr = curr.next
if deleted_fl:
self.count -= 1
def contains(self, data):
for n in self.iter():
if data == n:
return True
return False
def search(self, data):
curr = self.first
while curr:
if curr.data == data:
return curr
curr = curr.next
return None
def clear(self):
self.first = None
self.last = None
`
然后我们被要求实现一些功能。这就是其中之一:
def charCount(self, aggregated=False):
定义:
Returns the total number of characters contained in the nodes of the
linked list.
If the `aggregated' argument is True, the result should be a single
integer
representing the sum of character counts of all elements in the
LinkedList. If False,
the result should be a list of integers representing the count of
characters of each
node. In both cases, if the list is empty, return `None'. The aggregated
version of
this method should be O(1) and the dis-aggregated version should be O(n).
:param aggregated: If True, aggregate the counts into a single value. If
False, return
a list of counts.
:return: A single integer or list of integers as described above.
世界上什么是聚合的=这里的假应该是指什么?什么是";如果聚合参数为True";?
提前感谢
aggregated
是函数的参数,您可以在调用函数时传递该参数。例如,您可以这样调用函数:
list = LinkedList()
list.charCount(True)
在这种情况下,您传递的aggregated
参数的值为True
。
函数声明中的=False
部分意味着您不必为aggregated
参数传递值,在这种情况下,它将默认为False
。这是一个所谓的默认论点。