包接口
包接口的以下操作很有用:知道一个包是否为空,用一次操作就清空一个包,判断一个给定的项是否在包中,以及查看包中的每一项而不用清空包等等。
| 用户的包操作 | Bag类中的方法 |
|---|---|
| b = <class name>(<optional collection>) | __init__(self,sourceCollection = None) |
| b.isEmpty() | isEmpty(self) |
| len(b) | __len__(self) |
| str(b) | __str__(self) |
| item in b | __contains__(self,item); 如果包含了__iter__,就不需要该方法 |
| b1 + b2 | __add__(self,other) |
| b == anyObject | __eq__(self,other) |
| b.clear() | clear(self) |
| b.add(item) | add(self,item) |
| b.remove(item) | remove(self,item) |
开发一个基于数组的实现
由于这是一个基于数组的实现,所以ArrayBag类型的每一个对象,都包含了该包中的一个数组。这个数组可以是已经实现的Array类的一个实例,也可以是另一个基于数组的集合(例如Python的list类型)。
Array类
"""
File: arrays.py
An Array is a restricted list whose clients can use
only [], len, iter, and str.
To instantiate, use
<variable> = array(<capacity>, <optional fill value>)
The fill value is None by default.
"""
class Array(object):
"""Represents an array."""
def __init__(self, capacity, fillValue = None):
"""Capacity is the static size of the array.
fillValue is placed at each position."""
self._items = list()
for count in range(capacity):
self._items.append(fillValue)
def __len__(self):
"""-> The capacity of the array."""
return len(self._items)
def __str__(self):
"""-> The string representation of the array."""
return str(self._items)
Python 包接口:数组与链表实现解析

本文介绍了Python中包接口的设计,详细阐述了基于数组和链表的两种实现方式。ArrayBag和LinkedBag类分别实现了数组和链表的包接口,包括添加、删除、查找等操作。虽然两者在性能上略有不同,如数组实现的添加操作更快,删除较慢,但整体运行时间相似。此外,文章强调了接口的一致性和实现的多样性。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



