使用List建立最簡單的佇列(queue) - Python

Posted by: Max Chen | in Python | 1 year ago |

一個使用Python實作佇列的練習。

佇列:

  1. 具有先進先出(FIFO)的特性。
  2. 擁有兩種基本動作加入與刪除,而且使用 front 與 rear 兩個指標來分別指 向佇列的前端與尾端

實作佇列

# making a queue through array (this queue can't be reusable)
'''
create 建立空佇列。 
add 將新資料加入佇列的尾端,傳回新佇列。 
delete 刪除佇列前端的資料,傳回新佇列。 
front 傳回佇列前端的值。 
empty 若佇列為空集合,傳回真,否則傳回偽。
'''

class queue:

    # create
    def __init__(self,MAXSIZE):
        self.size = MAXSIZE
        self.rear = self.front = -1
        self.queue = [0] * MAXSIZE
        print(self.queue)

    def add(self,data):
        if self.rear == self.size-1:
            print('queue is full')
        else:
            self.rear += 1
            self.queue[self.rear] = data
    def delete(self):
        if self.front == self.rear:
            print('queue is empty')
        else:
            self.front += 1
            self.queue[self.front] = 0

    def front_value(self):
        print(self.queue[self.front+1])

    def isempty(self):
        if all(flag == 0 for flag in self.queue):
            return True
        else:
            return False

測試

#create
q = queue(10)
>>>[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

#isempty
q.isempty()
>>>True

#add
q.add(30)
q.add(50)

#show 
q.queue
>>>[30, 50, 0, 0, 0, 0, 0, 0, 0, 0]

#show front value
q.front_value()
>>>30

# delete front
q.delete()

#show front value
q.front_value()
>>>50

#show 
q.queue
>>>[0, 50, 0, 0, 0, 0, 0, 0, 0, 0]

Reference:

https://stackoverflow.com/questions/10666163/how-to-check-if-all-elements-of-a-list-match-a-condition

https://stackoverflow.com/questions/53513/how-do-i-check-if-a-list-is-empty

https://blog.csdn.net/yogima/article/details/80672254

https://www.delftstack.com/zh-tw/howto/python/python-local-variable-referenced-before-assignment/

https://blog.csdn.net/gaifuxi9518/article/details/81193296

https://www.books.com.tw/products/0010840854

Currently unrated
 or 

Subscribe

* indicates required

Recent Posts

Archive

2023
2022
2021

Categories

Apache 1

Data Science 2

Dbfit 1

Design Pattern 1

Devops 4

DigitalOcean 1

Django 1

English 3

Excel 5

FUN 4

Flask 3

Git 1

HackMD 1

Heroku 1

Html/Css 1

Linux 4

MDX 1

Machine Learning 2

Manufacture 1

Master Data Service 1

Mezzanine 18

Oracle 1

Postgresql 7

PowerBI 4

Powershell 4

Python 22

SEO 2

SQL Server 53

SQL Server Analytics Service 1

SQLite 1

Windows 1

database 8

work-experience 1

其他 1

投資入門 1

投資心得 2

時間管理 1

總體經濟 2

自我成長 3

資料工程 1

Tags

SEO(1) Github(2) Title Tag(2) ML(1) 李宏毅(1) SQL Server(18) Tempdb(1) SSMS(1) Windows(1) 自我成長(2) Excel(1) python Flask(1) python(5) Flask(2)

Authors

Max Chen (159)

Feeds

RSS / Atom

使用List建立最簡單的佇列(queue) - Python

© COPYRIGHT 2011-2022. Max的文藝復興. ALL RIGHT RESERVED.