Python 使用有序list构建简单的set

#!/usr/bin/python 
# -*- coding: utf-8 -*-

'''
Created on 2015-1-20
@author: beyondzhou
@name: test_sortedlinearset.py
'''

def test_sortedlinearset():
    
    # import mySet
    from sortedlinearset import mySet
    
    print 'Init a set named smith'
    smith = mySet()
    smith.add('112')
    smith.add('340')
    smith.add('121')
    
    print 'output smith set'
    for element in smith:
        print element
        
    print '\nInit a set named robin'
    robin = mySet()
    robin.add('112')
    robin.add('430')
    robin.add('111')
    
    print 'output robin set'
    for element in robin:
        print element
        
    print '\nunion of smith and robin'
    smithrobin = smith.union(robin)
    print 'output smithrobin set'
    for element in smithrobin:
        print element 
        
if __name__ == "__main__":
    test_sortedlinearset()

# Implementation of iter
class _SetIterator:
    def __init__(self, theList):
        self._setItems = theList
        self._curItem = 0
    def __iter__(self):
        return self
    def next(self):
        if self._curItem < len(self._setItems):
            item = self._setItems[self._curItem]
            self._curItem += 1
            return item
        else:
            raise StopIteration
        
# Implementation of the Set ADT using a sorted list
class mySet:
    # Creates an empty set instance
    def __init__(self):
        self._theElements = list()

    # Returns the number of items in the set
    def __len__(self):
        return len(self._theElements)

    # Determines if an element is in the set
    def __contains__(self, element):
        ndx = self._findPosition(element)
        return ndx < len(self) and self._theElements[ndx] == element

    # Determines if two set are equal
    def __eq__(self, setB):
        if len(self) != len(setB):
            return False
        else:
            for i in range(len(self)):
                if self._theElements[i] != setB._theElements[i]:
                    return False
            return True

    # Adds a new unique element to the set
    def add(self, element):
        if element not in self:
            ndx = self._findPosition(element)
            self._theElements.insert(ndx, element)

    # Removes an element from the set
    def remove(self, element):
        assert element in self, "The element must be in the set."
        ndx = self._findPosition(element)
        self._theElements.pop(ndx)

    # Determines if this set is a subset of setB
    def isSubsetOf(self, setB):
        for element in self:
            if element not in setB:
                return False
        return True

    # Returns an iterator for traversing the list of items
    def __iter__(self):
        return _SetIterator(self._theElements)

    # Finds the position of the element within the ordered list
    def _findPosition(self, element):
        theList = self._theElements
        low = 0
        high = len(theList) - 1
        while low <= high:
            mid = (high + low) / 2
            if theList[mid] == element:
                return mid
            elif element < theList[mid]:
                high = mid - 1
            else:
                low = mid + 1
        return low

    # Union action
    def union(self, setB):
        newSet = mySet()
        a = 0
        b = 0
        # Merge the two lists together until one is empty
        while a < len(self) and b < len(setB):
            valueA = self._theElements[a]
            valueB = setB._theElements[b]
            if valueA < valueB:
                newSet._theElements.append(valueA)
                a += 1
            elif valueA > valueB:
                newSet._theElements.append(valueB)
                b += 1
            else:      # Only one of the two duplicates are appended
                newSet._theElements.append(valueA)
                a += 1
                b += 1
        
        # If listA contains more items. append them to newList
        while a < len(self):
            newSet._theElements.append(self._theElements[a])
            a += 1
      
        # Or if listB contains more, append them to newList
        while b < len(setB):
            newSet._theElements.append(setB._theElements[b])
            b += 1

        return newSet

Init a set named smith
output smith set
112
121
340

Init a set named robin
output robin set
111
112
430

union of smith and robin
output smithrobin set
111
112
121
340
430

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值