[英]How is the global variable being incremented when it's not being directly specified?
我正在做一個小項目,正在將隊列實現為循環數組。 作為挑戰,我被分配為在實現此ADT時不使用任何列表功能(如append)。 假定僅在隊列已滿時才需要調整其大小。 當我通過調試器運行代碼並逐步調試時,我發現問題圍繞着我的self.read值(讀取指針)展開,該值是有問題的全局變量。 這讓我感到困惑,因為我兩個受影響的函數都不會增加我的指針。 誰能為我闡明這個問題?
此類的編碼為:
class CircularQueue(object):
def __init__(self, capacity=2):
"""
Initialize the queue to be empty with a fixed capacity
:param capacity: Initial size of the queue
"""
self.capacity = capacity
self.size = 0
self.list = [0] * self.capacity
self.sum = 0
self.read = 0
self.write = 0
def __eq__(self, other):
return self.capacity == other.capacity
and self.size == other.size
and self.read == other.read
and self.write == other.write
def __str__(self):
if self.size == 0:
return "Queue is empty"
content = ""
while ((self.read + 1) % self.size) != self.write:
content = content + str(self.list[self.read]) + " -> "
self.read = (self.read + 1) % self.size
content = content[:-3]
return f"Contents: {content}"
__repr__ = __str__
我感興趣的部分是我的入隊和調整大小功能:
def resize(self):
bigger = [None] * (self.capacity * 2) #create bigger queue
b_ind = 0
read_ptr = self.read
while read_ptr != (self.write + 1): #iterate through old queue to copy into new queue
bigger[b_ind] = self.list[read_ptr]
b_ind += 1
read_ptr += 1
self.capacity *= 2 #setting capacity
self.list = bigger #setting new list as queue
self.read = 0 #normalize queue
self.write = b_ind
def enqueue(self, number):
if self.size == 0: #if queue was originally empty
self.list[self.read] = number
self.write += 1
else:
self.list[self.write] = number #add onto end of queue
if ((self.write + 1) % self.capacity == self.read): #resize if queue loops back and the write pointer is the same as the read pointer
self.resize()
else:
self.write = (self.write + 1) % self.capacity #set write pointer
self.sum += number #add to sum
self.size += 1 # increment size
這是我為代碼運行的測試用例:
queue = CircularQueue()
queue.enqueue(23)
queue.enqueue(42)
queue.enqueue(2)
queue.enqueue(195)
print(queue)
您可以在打印時更改隊列的狀態。 print()
調用__str__
,該方法會改變您的狀態:
self.read = (self.read + 1) % self.size
使用局部變量而不是self.read
:
def __str__(self):
if self.size == 0:
return "Queue is empty"
content = ""
read = self.read
while (read % self.capacity) != self.write:
if content:
content += ' -> '
content += str(self.list[read])
read = (read + 1) % self.capacity
return f"Contents: {content}"
注意while
循環條件; 您想查看當前的讀取位置是否與write
位置不同(意味着您可以顯示當前值),而不是下一個位置,並且希望以該容量來回繞。
我對分隔符的處理進行了一些調整,以僅在至少一個條目已添加到content
,才在值之間添加箭頭,從而避免了再次刪除一部分的麻煩。
使用固定的__str__
方法的演示(未進行其他更改):
>>> queue = CircularQueue()
>>> print(queue)
Queue is empty
>>> queue.enqueue(23)
>>> print(queue)
Contents: 23
>>> queue.enqueue(42)
>>> print(queue)
Contents: 23 -> 42
>>> queue.enqueue(2)
>>> print(queue)
Contents: 23 -> 42 -> 2
>>> queue.enqueue(195)
>>> print(queue)
Contents: 23 -> 42 -> 2 -> 195
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.