队列实现显示功能错误

时间:2019-04-29 17:22:36

标签: python queue

class Queue:
    def __init__(self):   '''initialization of function'''
        self.items = []
    def is_empty(self):   '''Checking if queue is empty or not'''
        return self.items == []
    def enqueue(self, data): '''Adding value '''
        self.items.append(data)
    def dequeue(self):     ''' Removing value'''
        return self.items.pop(0)
    def dis(self):  '''Printing the stored item in queue'''
        print(items)

Queue初始化之后:

 q = Queue()
 while True:
     print('enqueue <value>')
     print('dequeue')
     print('dis')
     print('quit')
     do = input('What would you like to do? ').split()
     operation = do[0].strip().lower()
     if operation == 'enqueue':
         q.enqueue(int(do[1]))
     elif operation == 'dequeue':
         if q.is_empty():
             print('Queue is empty.')
         else:
             print('Dequeued value: ', q.dequeue())
     elif operation == 'dis':
         q.dis()
     elif operation == 'quit':
         break
     else:
         print("Enter the correct operation")

我无法显示Queue中排队的项目。如何使用dis()方法显示其中的项目?

2 个答案:

答案 0 :(得分:4)

认为您应该打印self.items(而不是项目)

def dis(self):  '''Printing the stored item in queue'''
    print(self.items)

这将使用标准格式输出列表,而不是非常漂亮,因此您可能需要为漂亮打印添加一些额外的逻辑。

如果要限制队列大小,可以通过简单地忽略超过一定限制的项目来实现。为此,您需要实现一个限制以及检查该限制的逻辑。例如:

class Queue:
    def __init__(self, size=8):   '''initialization of function'''
        self.items = []
        self.size = size
    def is_empty(self):   '''Checking if queue is empty or not'''
        return self.items == []
    def enqueue(self, data): '''Adding value '''
        if len(self.items) < self.size:
            self.items.append(data)
        else:
            pass # behavior when queue is already full
    def dequeue(self):     ''' Removing value'''
        return self.items.pop(0)
    def dis(self):  '''Printing the stored item in queue'''
        print(items)

答案 1 :(得分:1)

class Queue:
    items=[]
    size=5
    def __init__(self):
        self.items = []

    def is_empty(self):
        return self.items == []
    def enqueue(self, data):
        self.items.append(data)

    def dequeue(self):
        return self.items.pop(0)
    def dis(self):
        print(self.items)
    def is_full(self):
        if (len(self.zitems)>5):
            print("Queue is full")
        else:
            print("Not full")

将项目= []初始化,然后在dis方法中添加self.items。此外,您可以检查队列的大小是否已满