[GeneralAlgorithm] Bounded Queue Algorithm 有界队列算法 (in Python)

Bounded Queue Algorithm (in Python)

简易有界队列算法,携Sample Test部分

class BoundedQueue: 
    def __init__(self, capacity):
        assert isinstance(capacity, int), ('Error: Type error: {}'.format(type(capacity)))
        self.__items = []
        self.__capacity = capacity
 
    
    def enqueue(self, item):
        if len(self.__items) >= self.__capacity:     
            raise Exception('Error: Queue is full')
        self.__items.append(item)
        
  
    def dequeue(self):
        if len(self.__items) <= 0:            
            raise Exception('Error: Queue is empty')                
        return self.__items.pop(0)            
    
          
    def peek(self):
        if len(self.__items) <= 0:            
            raise Exception('Error: Queue is empty')        
        return self.__items[0]
        
      
    def isEmpty(self):
        return len(self.__items) == 0        
    
        
    def isFull(self):
        return len(self.__items) == self.__capacity
    
        
    def size(self):
        return len(self.__items)        
    
       
    def capacity(self):
        return self.__capacity
    
  
    def clear(self):
        self.__items = []

    
    def __str__(self):
        str_exp = ""        
        for item in self.__items:            
            str_exp += (str(item) + " ")                    
        return str_exp
        
    
    def __repr__(self):
        return str(self) + " Max=" + str(self.__capacity)

Test Sample:

def main():
    # Test bounded queue constructor
    bq = BoundedQueue(3)
    print("My bounded queue is:", bq)
    print(repr(bq))
    print("Is my bounded queue empty?", bq.isEmpty())
    print('----------------------------------')



    '''
    # 1. To Do: complete Test 1 according to lab description
    # Test when we try to dequeue from an EMPTY queue
    try:
        ## To Do: Write your own test

    except Exception as dequeueError:
        ## To Do: Write a way to handle it
    '''
    try:
        print("Try to dequeue an empty bounded queue...")
        frontValue = bq.dequeue()
    except Exception as msg:
        print(msg)
    print('----------------------------------')



    '''
    # 2. To Do: complete Test 2 according to lab description
    # Test adding one element to queue
    
    ## Your test code goes here...
    '''
    bq.enqueue('bob')
    print(bq)
    print(str(bq))
    print("Is my bounded queue empty?", bq.isEmpty())    
    print('----------------------------------')


    
    '''
    # 3. Uncomment and run Test 3
    # Test adding more elements to queue
    '''
    bq.enqueue("eva")
    bq.enqueue("paul")
    print(repr(bq))
    print("Is my bounded queue full?", bq.isFull())
    print("There are", bq.size(), "elements in my bounded queue.")
    print('----------------------------------')

 
    '''
    # 4. To Do: complete Test 4 according to lab description
    # Test trying to add an element to a FULL queue
    
    ## Your test code goes here...hint: look at dequeuing from EMPTY queue
    '''
    try:
        print('Try to enqueue a full bounded queue...')
        bq.enqueue("eden")
    except Exception as msg:
        print(msg)
    print('----------------------------------')

    
    '''
    # 5. Uncomment and run Test 5
    # Test removing element from full queue
    '''
    item = bq.dequeue()
    print(repr(bq))
    print(item, "was first in the bounded queue:", bq)
    print("There are", bq.size(), "elements in my bounded queue.")
    print('----------------------------------')

    
    '''
    # 6. Uncomment and run Test 6
    # Test capacity of queue
    '''
    print("Total capacity is:", bq.capacity())


    '''
    # 7. To Do: Uncomment print statements, one at a time
    # Can we just access private capacity attribute directly outside of Class definition?
    '''
    #print(bq.capacity)
    #print(bq.__capacity)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值