Python 基于数组、链表实现的包接口

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

包接口

包接口的以下操作很有用:知道一个包是否为空,用一次操作就清空一个包,判断一个给定的项是否在包中,以及查看包中的每一项而不用清空包等等。

包操作及其方法
用户的包操作 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)

    def __iter__(self):
        """Supports iteration over a view of an array."""
        return iter(self._items)

    def __getitem__(self, index):
        """Subscript operator for access at index."""
        return self._items[index]

    def __setitem__(sel
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值