我使用python实现循环队列,但却发现与数组队列时间差别不大

我使用python实现循环队列,但却发现与数组队列时间差别不大

# 具体遇到的问题
我使用python实现循环队列,但却发现与数组队列时间差别不大
# 报错信息的截图
python:

http://img1.sycdn.imooc.com//climg/5fdaf1c90907d94105680067.jpg

http://img1.sycdn.imooc.com//climg/5fdb13df0938fbfb05790073.jpg

java:

http://img1.sycdn.imooc.com//climg/5fdb12b209c3f1df01520098.jpg

# 尝试过的解决思路和结果

我完全是按照同样的思想实现的,可是两者差别却不像java那样明显
我想知道这是python语言特性的问题,还是我的实现方法有误?

import array as builtin_array


class LoopQueue:
def __init__(self, capacity: int = 20):
self._typeCode = 'h'
       self.__data = builtin_array.array(self._typeCode, (0, ) * (capacity + 1))
# print(self.__data)
       # print(len(self.__data))
       self.__front = 0
       self.__tail = 0

   def getCapacity(self) -> int:
return len(self.__data) - 1

   def isEmpty(self) -> bool:
return self.__front == self.__tail

def enqueue(self, e) -> None:
if (self.__tail + 1) % len(self.__data) == self.__front:
self.__resize(2 * self.getCapacity())
self.__data[self.__tail] = e
self.__tail = (self.__tail + 1) % len(self.__data)

def dequeue(self):
if self.isEmpty():
raise ValueError("不可从空队列中弹出元素!")
temp = self.__data[self.__front]
# 这步可要可不要
       # self.__data[self.__front] = 0
       self.__front = (self.__front + 1) % len(self.__data)
if self.getSize() <= self.getCapacity() / 4 and int(self.getCapacity() / 2):
self.__resize(int(self.getCapacity() / 2))
return temp

def getFront(self):
if self.isEmpty():
raise ValueError("不可从空队列中查看元素!")
return self.__data[self.__front]

def getSize(self) -> int:
if self.__tail >= self.__front:
return self.__tail - self.__front
else:
return len(self.__data) - self.__front + self.__tail

def __resize(self, newCapacity: int) -> None:
tempArray = builtin_array.array(self._typeCode, (0, ) * (newCapacity + 1))
i = 0
       for i in range(self.getSize()):
tempArray[i] = self.__data[(self.__front + i) % len(self.__data)]
self.__front = 0
       # 这里很重要,range不会为i加一,需要我们自己加
       self.__tail = i + 1
       self.__data = tempArray

def __str__(self):
string = "Queue: size=%d, capacity=%d, front[" % (self.getSize(), self.getCapacity())
i = self.__front
while not i == self.__tail:
string += str(self.__data[i])
if not (i + 1) % len(self.__data) == self.__tail:
string += ", "
           i = (i + 1) % len(self.__data)
string += "] tail"
       return string


if __name__ == '__main__':
loop_queue = LoopQueue(5)
# for i in range(100):
   #     loop_queue.enqueue(i)
   #     if i % 3 == 0:
   #         loop_queue.dequeue()
   #     print(loop_queue)

   for i in range(100):
loop_queue.enqueue(i)
for i in range(100):
loop_queue.dequeue()

import random

from ep2_SelectionSort.Clocker import clock
from ep5_Queue.ArrayQueue import ArrayQueue
from ep5_Queue.LoopQueue import LoopQueue


@clock
def timer(capacity, queueInstance):
for i in range(capacity):
queueInstance.enqueue(random.randint(0, 2**15 - 1))
for i in range(capacity):
queueInstance.dequeue()
return capacity


if __name__ == '__main__':
capacity = 1000000
   arrayQueue = ArrayQueue()
loopQueue = LoopQueue()
timer(capacity, arrayQueue)
timer(capacity, loopQueue)
import time


def clock(func):
def clocked(*args):
t0 = time.perf_counter()
result = func(*args)
elapsed = time.perf_counter() - t0
name = func.__name__
       print('Time elapsed: %0.8fs, sequence length=%d' % (elapsed, result))
return result
return clocked

在这里输入代码,可通过选择【代码语言】突出显示

正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

3回答
提问者 Mr__Xin 2020-12-21 00:22:45

import array as builtin_array


class LoopQueue:
def __init__(self, capacity: int = 20):
# 全部数据类型均为有符号数
if capacity <= 0:
raise ValueError("容量不可为负或零!")
elif capacity <= 2 ** 15 - 1:
self._typeCode = 'h'
elif capacity <= 2 ** 31 - 1:
self._typeCode = 'l'
elif capacity <= 2 ** 63 - 1:
self._typeCode = 'q'
self.__data = builtin_array.array(self._typeCode, (0, ) * (capacity + 1))
# print(self.__data)
# print(len(self.__data))
self.__front = 0
self.__tail = 0

def getCapacity(self) -> int:
return len(self.__data) - 1

def isEmpty(self) -> bool:
return self.__front == self.__tail

def enqueue(self, e) -> None:
if (self.__tail + 1) % len(self.__data) == self.__front:
self.__resize(2 * self.getCapacity())
self.__data[self.__tail] = e
self.__tail = (self.__tail + 1) % len(self.__data)

def dequeue(self):
if self.isEmpty():
raise ValueError("不可从空队列中弹出元素!")
temp = self.__data[self.__front]
# 这步可要可不要
# self.__data[self.__front] = 0
self.__front = (self.__front + 1) % len(self.__data)
if self.getSize() <= self.getCapacity() / 4 and int(self.getCapacity() / 2):
self.__resize(int(self.getCapacity() / 2))
return temp

def getFront(self):
if self.isEmpty():
raise ValueError("不可从空队列中查看元素!")
return self.__data[self.__front]

def getSize(self) -> int:
if self.__tail >= self.__front:
return self.__tail - self.__front
else:
return len(self.__data) - self.__front + self.__tail

def __resize(self, newCapacity: int) -> None:
tempArray = builtin_array.array(self._typeCode, (0, ) * (newCapacity + 1))
i = 0
for i in range(self.getSize()):
tempArray[i] = self.__data[(self.__front + i) % len(self.__data)]
self.__front = 0
# 这里很重要,range不会为i加一,需要我们自己加
self.__tail = i + 1
self.__data = tempArray

def __str__(self):
string = "Queue: size=%d, capacity=%d, front[" % (self.getSize(), self.getCapacity())
i = self.__front
while not i == self.__tail:
string += str(self.__data[i])
if not (i + 1) % len(self.__data) == self.__tail:
string += ", "
i = (i + 1) % len(self.__data)
string += "] tail"
return string
import random

from ep2_SelectionSort.Clocker import clock
from ep5_Queue.ArrayQueue import ArrayQueue
from ep5_Queue.LoopQueue import LoopQueue


@clock
def timer(capacity, queueInstance):
for i in range(capacity):
queueInstance.enqueue(random.randint(0, 2 ** 15 - 1))
for i in range(capacity):
queueInstance.dequeue()
return capacity


if __name__ == '__main__':
capacity = 10000000
arrayQueue = ArrayQueue()
loopQueue = LoopQueue()
timer(capacity, arrayQueue)
timer(capacity, loopQueue)
​import time


def clock(func):
def clocked(*args):
t0 = time.perf_counter()
result = func(*args)
elapsed = time.perf_counter() - t0
name = func.__name__
print('Time elapsed: %0.8fs, sequence length=%d' % (elapsed, result))
return result
return clocked


提问者 Mr__Xin 2020-12-18 23:05:34
import array as builtin_array
import random


class Array:
def __init__(self, capacity: int = 20):
self._typeCode = 'h'
self.__data = builtin_array.array(self._typeCode)
# self.__capacity = capacity
for i in range(capacity):
self.__data.append(0)
self.__size = 0

# def check(self):
# if len(self.__data) == self.__capacity:
# raise

def getSize(self):
return self.__size

def getCapacity(self):
return len(self.__data)

def isEmpty(self):
return self.__size == 0

def add(self, index, e):
if index < 0 or index > self.__size:
raise ValueError("索引不能小于0且不能大于容量!")
if self.__size == len(self.__data):
self.__resize(2 * len(self.__data))
for i in range(self.__size - 1, index - 1, -1):
self.__data[i+1] = self.__data[i]
self.__data[index] = e
self.__size += 1

def addFirst(self, e):
self.add(0, e)

def addLast(self, e):
self.add(self.__size, e)

def get(self, index):
if index < 0 or index >= self.__size:
raise ValueError("索引不能小于0且不能大于等于容量!")
return self.__data[index]

def getFirst(self):
return self.get(0)

def getLast(self):
return self.get(self.__size - 1)

def set(self, index, e):
if index < 0 or index >= self.__size:
raise ValueError("索引不能小于0且不能大于等于容量!")
self.__data[index] = e

def isContains(self, e):
for i in range(self.__size):
if self.__data[i] == e:
return True
return False

def find(self, e, isFindAll: bool = False):
tempArray = builtin_array.array(self._typeCode)
for i in range(self.__size):
if self.__data[i] == e:
if isFindAll:
tempArray.append(i)
else:
return i
return tempArray if len(tempArray) else -1

def remove(self, index):
if index < 0 or index >= self.__size:
raise ValueError("索引不能小于0且不能大于等于容量!")
temp = self.__data[index]
for i in range(index, self.__size - 1):
self.__data[i] = self.__data[i + 1]
self.__size -= 1
self.__data[self.__size] = 0
if self.__size == int(len(self.__data) / 2) and int(len(self.__data) / 2):
self.__resize(int(len(self.__data) / 2))
return temp

def removeFirst(self):
return self.remove(0)

def removeLast(self):
return self.remove(self.__size - 1)

def removeElement(self, e, isRemoveAll: bool = False):
if isRemoveAll:
tempArray = self.find(e, isFindAll=True)
if tempArray == -1 or not len(tempArray):
return None
i = 0
for ins in tempArray:
self.remove(ins - i)
i += 1
else:
index = self.find(e, isFindAll=False)
if index != -1:
self.remove(index)

def __resize(self, newCapacity: int):
# print(self._typeCode)
newData = builtin_array.array(self._typeCode)
for i in range(newCapacity):
newData.append(0)
for i in range(self.__size):
newData[i] = self.__data[i]
self.__data = newData
# self.__capacity = newCapacity

def __str__(self):
# string = "Array: size=%d, capacity=%d\n[" % (self.__size, self.__capacity)
string = "Array: size=%d, capacity=%d\n[" % (self.__size, len(self.__data))
for i in range(self.__size):
string += str(self.__data[i])
if not i == self.__size - 1:
string += ", "
string += "]"
return string
from ep3_Array.Array import Array


class ArrayQueue:
def __init__(self, capacity: int = 20):
self.__array = Array(capacity)

def enqueue(self, e):
self.__array.addLast(e)

def dequeue(self):
self.__array.removeLast()

def getFront(self):
self.__array.getFirst()

def getSize(self):
return self.__array.getSize()

def isEmpty(self):
return self.__array.isEmpty()

def getCapacity(self):
return self.__array.getCapacity()

def __str__(self):
string = "Queue: front ["
for i in range(self.getSize()):
string += str(self.__array.get(i))
if not i == self.getSize() - 1:
string += ", "
string += "] tail"
return string


liuyubobobo 2020-12-17 16:34:02

我再看一眼你的 ArrayQueue 的 Python 代码?

  • 提问者 Mr__Xin #1
    import array as builtin_array
    import random


    class Array:
    def __init__(self, capacity: int = 20):
    self._typeCode = 'h'
    self.__data = builtin_array.array(self._typeCode)
    # self.__capacity = capacity
    for i in range(capacity):
    self.__data.append(0)
    self.__size = 0

    # def check(self):
    # if len(self.__data) == self.__capacity:
    # raise

    def getSize(self):
    return self.__size

    def getCapacity(self):
    return len(self.__data)

    def isEmpty(self):
    return self.__size == 0

    def add(self, index, e):
    if index < 0 or index > self.__size:
    raise ValueError("索引不能小于0且不能大于容量!")
    if self.__size == len(self.__data):
    self.__resize(2 * len(self.__data))
    for i in range(self.__size - 1, index - 1, -1):
    self.__data[i+1] = self.__data[i]
    self.__data[index] = e
    self.__size += 1

    def addFirst(self, e):
    self.add(0, e)

    def addLast(self, e):
    self.add(self.__size, e)

    def get(self, index):
    if index < 0 or index >= self.__size:
    raise ValueError("索引不能小于0且不能大于等于容量!")
    return self.__data[index]

    def getFirst(self):
    return self.get(0)

    def getLast(self):
    return self.get(self.__size - 1)

    def set(self, index, e):
    if index < 0 or index >= self.__size:
    raise ValueError("索引不能小于0且不能大于等于容量!")
    self.__data[index] = e

    def isContains(self, e):
    for i in range(self.__size):
    if self.__data[i] == e:
    return True
    return False

    def find(self, e, isFindAll: bool = False):
    tempArray = builtin_array.array(self._typeCode)
    for i in range(self.__size):
    if self.__data[i] == e:
    if isFindAll:
    tempArray.append(i)
    else:
    return i
    return tempArray if len(tempArray) else -1

    def remove(self, index):
    if index < 0 or index >= self.__size:
    raise ValueError("索引不能小于0且不能大于等于容量!")
    temp = self.__data[index]
    for i in range(index, self.__size - 1):
    self.__data[i] = self.__data[i + 1]
    self.__size -= 1
    self.__data[self.__size] = 0
    if self.__size == int(len(self.__data) / 2) and int(len(self.__data) / 2):
    self.__resize(int(len(self.__data) / 2))
    return temp

    def removeFirst(self):
    return self.remove(0)

    def removeLast(self):
    return self.remove(self.__size - 1)

    def removeElement(self, e, isRemoveAll: bool = False):
    if isRemoveAll:
    tempArray = self.find(e, isFindAll=True)
    if tempArray == -1 or not len(tempArray):
    return None
    i = 0
    for ins in tempArray:
    self.remove(ins - i)
    i += 1
    else:
    index = self.find(e, isFindAll=False)
    if index != -1:
    self.remove(index)

    def __resize(self, newCapacity: int):
    # print(self._typeCode)
    newData = builtin_array.array(self._typeCode)
    for i in range(newCapacity):
    newData.append(0)
    for i in range(self.__size):
    newData[i] = self.__data[i]
    self.__data = newData
    # self.__capacity = newCapacity

    def __str__(self):
    # string = "Array: size=%d, capacity=%d\n[" % (self.__size, self.__capacity)
    string = "Array: size=%d, capacity=%d\n[" % (self.__size, len(self.__data))
    for i in range(self.__size):
    string += str(self.__data[i])
    if not i == self.__size - 1:
    string += ", "
    string += "]"
    return string
    from ep3_Array.Array import Array


    class ArrayQueue:
    def __init__(self, capacity: int = 20):
    self.__array = Array(capacity)

    def enqueue(self, e):
    self.__array.addLast(e)

    def dequeue(self):
    self.__array.removeLast()

    def getFront(self):
    self.__array.getFirst()

    def getSize(self):
    return self.__array.getSize()

    def isEmpty(self):
    return self.__array.isEmpty()

    def getCapacity(self):
    return self.__array.getCapacity()

    def __str__(self):
    string = "Queue: front ["
    for i in range(self.getSize()):
    string += str(self.__array.get(i))
    if not i == self.getSize() - 1:
    string += ", "
    string += "] tail"
    return string


    2020-12-17 22:52:31
  • liuyubobobo 回复 提问者 Mr__Xin #2

    我想在我的本地测试一下你的代码,你之前贴的 LoopQueue 和相关的测试代码格式是乱的,可能是慕课网的 bug,能不能重新贴一下?上面 Array 和 ArrayQueue 的代码格式没有问题。

    2020-12-20 20:54:57
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
算法与数据结构
  • 参与学习       2583    人
  • 解答问题       1082    个

慕课网算法名师Liuyubobobo,5年集大成之作 从0到工作5年,算法与数据结构系统解决方案

了解课程
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师