标签:optional clip 集合类 objects tps 关系 item back 自身
用户的包操作 | 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 ) |
def remove( self, item ): """ Preconditon: item is in self. Raise: KeyError if item is not in self. Postcondition: item is removed from self. """ |
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Lijunjie
""" File: baginterface.py Author: Lijunjie """
class BagInterface( object ): """Interface for all bag types."""
#Constructor def __init__( self, sourceCollection = None ): """Sets the initial state of self, which includes the contents of sourceCollection, if it‘s present.""" pass
#Accessor methods def isEmpty( self ): """Return True if len( self ) == 0, or False otherwise.""" return True
def __len__( self ): """Returns the number of items in self.""" return 0
def __str__( self ): """Return the string representation of self.""" return ""
def __iter__( self ): """Supports iteration over a view of self.""" return None
def __add__( self, other ): """Return a new bag containing the contents of self and other""" return None
def __eq__( self, other ): """Return True if self equals other, otherwise False.""" return False
#Mutator methods def clear( self ): """Makes self become empty.""" pass
def add( self, item ): """Adds item to self.""" pass
def remove( self, item ): """ Precondition: item is in self. Raise: KeyError if item is not in self. Postcondition: item is removed form self. """ pass |
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Lijunjie
""" File: arraybag.py Author: Lijunjie """
from arrays import Array
class ArrayBag( object ): """An array-based bag implementation."""
#Class variable DEFAULT_CAPACTIY = 10
#Constructor def __init__( self, sourceCollection = None ): """Sets the initial state of self, which includes the contents of sourceCollection, if it‘s present.""" self._items = Array( ArrayBag.DEFAULT_CAPACTIY ) self._size = 0 if sourceCollection: for item in sourceCollection: self.add( item ) |
#Accessor methods def isEmpty( self ): """Return True if len( self ) == 0, or False otherwise.""" return len( self ) == 0
def __len__( self ): """Returns the number of items in self.""" return self._size
#Mutator methods def clear( self ): """Makes self become empty.""" self_size = 0 self._items = Array( ArrayBag.DEFAULT_CAPACTIY )
def add( self, item ): """Adds item to self.""" #Check array memory here and increase it if necessary. self._items[len( self )] = item self._size += 1 |
def __iter__( self ): """Supports iteration over a view of self.""" cursor = 0 while cursor < len( self ): yield self._items[cursor] cursor += 1 |
def __str__( self ): """Return the string representation of self.""" return "{" + ", ".join( map( str, self ) ) + "}" |
def __add__( self, other ): """Return a new bag containing the contents of self and other""" result = ArrayBag( self ) for item in other: result.add( item ) return result |
def __eq__( self, other ): """Return True if self equals other, otherwise False.""" if self is other: return True if type( self ) != type( other ) or len( self ) != len( other ): return False for item in self: if not item in other: return False return True |
def remove( self, item ): """ Precondition: item is in self. Raise: KeyError if item is not in self. Postcondition: item is removed form self. """ if not item in self: raise KeyError( str(item) + " not in bag." ) #Search for index of target item. targetIndex = 0 for targetItem in self: if targetItem == item: break targetIndex += 1
#Shift items for i in range( targetIndex, len( self ) - 1 ): self._items[i] = self._items[i + 1] #Decrement logical size self._size -= 1 #Check array memory here and decrease it if necessary |
""" File: linkedbag.py Author: Lijunjie """
from node import Node
class LinkedBag( object ): """An link-based bag implementation."""
#Constructor def __init__( self, sourceCollection = None ): """Sets the initial state of self, which includes the contents of sourceCollection, if it‘s present.""" self._items = None self._size = 0 if sourceCollection: for item in sourceCollection: self.add( item ) |
def __iter__( self ): """Supports iteration over a view of self.""" cursor = self._items while not cursor is None: yield cursor.data cursor = cursor.next |
def clear( self ): """Makes self become empty.""" self._size = 0 self._items = None |
def add( self, item ): """Adds item to self.""" self._items = Node( item, self._items ) self._size += 1 |
def remove( self, item ): """ Precondition: item is in self. Raise: KeyError if item is not in self. Postcondition: item is removed form self. """ if not item in self: raise KeyError( str(item) + " not in bag." ) #Search for the node containing target item. #probe will point to the target node, and trailer will point to #the one before it, if it exists. probe = self._items trailer = None for targetItem in self: if targetItem == item: break trailer = probe probe = probe.next # Unhook the node to be deleted, either the first one or the #one thereafter if probe == self._items: self._items = self._items.next else: trailer.next = probe.next #Decrement logical size self._size -= 1 |
##!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Lijunjie
""" FIle: testbag.py Author: Lijunjie A test program for bag implementations. """
from arraybag import ArrayBag from linkedbag import LinkedBag
def test( bagType ): """Expects a bag type as argument and runs some tests on objects of that type. """
lyst = [2018, 23, 1995] print( "The list of items added is:", lyst ) b1 = bagType( lyst ) print( "Expect 3:", len( b1 ) ) print( "Expect the bag‘s string:", b1 ) print( "Expect True:", 2018 in b1 ) print( "Expect False:", 2013 in b1 ) print( "Expect the items on spearate lines:" ) for item in b1: print( item ) b1.clear() print( "Expect {}:", b1 ) b1.add( 25 ) b1.remove( 25 ) print( "Expect {}:", b1 ) b1 = bagType( lyst ) b2 = bagType( b1 ) print( "Expect True:", b1 == b2 ) print( "Expect False:", b1 is b2 ) print( "Expect two of each items:", b1 + b2 ) for item in lyst: b1.remove( item ) print( "Expect crash with keyError:" ) b2.remove( 99 )
if __name__ == "__main__": #test( ArrayBag ) test( LinkedBag) |
标签:optional clip 集合类 objects tps 关系 item back 自身
原文地址:https://www.cnblogs.com/lijunjie9502/p/9892534.html