鱼C论坛

 找回密码
 立即注册
查看: 2567|回复: 2

[已解决]测验1: 实现队列

[复制链接]
发表于 2022-10-21 18:48:37 | 显示全部楼层 |阅读模式
10鱼币
本帖最后由 KeyError 于 2022-10-21 18:50 编辑

定义Myduilie类,有以下函数:
        def push(x: int) -> None:将x添加到队列的末尾
        def pop() -> int:从队列的开头移除并返回元素
        def peek() -> int:返回队列开头的元素
        def empty() -> bool:返回队列是否为空
最佳答案
2022-10-21 18:48:38
类名有所修改,此外还使用了typing库中的Any和Optional这两个类来注释返回值类型。
  1. from typing import Any, Optional


  2. class _Node:
  3.     """节点类"""

  4.     def __init__(self, v: Any) -> None:
  5.         self.__value = v
  6.         self.__next = None

  7.     def get_value(self) -> Any:
  8.         """获取节点保存的值"""
  9.         return self.__value

  10.     def get_next(self) -> Optional['_Node']:
  11.         """获取下一个节点"""
  12.         return self.__next

  13.     def set_next(self, n: Optional['_Node']) -> None:
  14.         """设置下一个节点"""
  15.         self.__next = n


  16. class QueueError(Exception):
  17.     """自定义队列异常"""

  18.     def __init__(self, msg: str) -> None:
  19.         """使用提示信息实例化一个队列异常对象"""
  20.         self.val = msg

  21.     def __str__(self) -> str:
  22.         return self.val


  23. class MyQueue:
  24.     """自定义队列"""

  25.     def __init__(self) -> None:
  26.         """实例化自定义队列,使用队首、队尾、长度三个属性记录队列信息"""
  27.         self.__head: Optional[_Node] = None  # 队首,_Node类型或者为None
  28.         self.__tail: Optional[_Node] = None  # 队尾,_Node类型或者为None
  29.         self.__len: int = 0  # 队列长度

  30.     def push(self, x: int) -> None:
  31.         """将x添加到队列末尾"""
  32.         node = _Node(x)
  33.         if self.__len <= 0:
  34.             self.__head = self.__tail = node
  35.         else:
  36.             self.__tail.set_next(node)
  37.             self.__tail = node
  38.         self.__len += 1

  39.     def pop(self) -> int:
  40.         """从队列开头移除并返回元素"""
  41.         if self.__len > 0:
  42.             node = self.__head
  43.             self.__head = node.get_next()
  44.             self.__len -= 1
  45.             return node.get_value()
  46.         raise QueueError('队列为空')

  47.     def peek(self) -> Optional[int]:
  48.         """查看队列开头的元素,如果队列为空则返回None"""
  49.         if self.__len <= 0:
  50.             return self.__head.get_value()
  51.         return None

  52.     def empty(self) -> bool:
  53.         """返回队列是否为空"""
  54.         return self.__len == 0


  55. if __name__ == '__main__':
  56.     q = MyQueue()
  57.     for i in range(5):
  58.         q.push(i)
  59.     print(q.empty())
  60.     for i in range(5):
  61.         print(q.pop())
  62.     q.pop()  # 抛出异常
复制代码

最佳答案

查看完整内容

类名有所修改,此外还使用了typing库中的Any和Optional这两个类来注释返回值类型。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-10-21 18:48:38 | 显示全部楼层    本楼为最佳答案   
类名有所修改,此外还使用了typing库中的Any和Optional这两个类来注释返回值类型。
  1. from typing import Any, Optional


  2. class _Node:
  3.     """节点类"""

  4.     def __init__(self, v: Any) -> None:
  5.         self.__value = v
  6.         self.__next = None

  7.     def get_value(self) -> Any:
  8.         """获取节点保存的值"""
  9.         return self.__value

  10.     def get_next(self) -> Optional['_Node']:
  11.         """获取下一个节点"""
  12.         return self.__next

  13.     def set_next(self, n: Optional['_Node']) -> None:
  14.         """设置下一个节点"""
  15.         self.__next = n


  16. class QueueError(Exception):
  17.     """自定义队列异常"""

  18.     def __init__(self, msg: str) -> None:
  19.         """使用提示信息实例化一个队列异常对象"""
  20.         self.val = msg

  21.     def __str__(self) -> str:
  22.         return self.val


  23. class MyQueue:
  24.     """自定义队列"""

  25.     def __init__(self) -> None:
  26.         """实例化自定义队列,使用队首、队尾、长度三个属性记录队列信息"""
  27.         self.__head: Optional[_Node] = None  # 队首,_Node类型或者为None
  28.         self.__tail: Optional[_Node] = None  # 队尾,_Node类型或者为None
  29.         self.__len: int = 0  # 队列长度

  30.     def push(self, x: int) -> None:
  31.         """将x添加到队列末尾"""
  32.         node = _Node(x)
  33.         if self.__len <= 0:
  34.             self.__head = self.__tail = node
  35.         else:
  36.             self.__tail.set_next(node)
  37.             self.__tail = node
  38.         self.__len += 1

  39.     def pop(self) -> int:
  40.         """从队列开头移除并返回元素"""
  41.         if self.__len > 0:
  42.             node = self.__head
  43.             self.__head = node.get_next()
  44.             self.__len -= 1
  45.             return node.get_value()
  46.         raise QueueError('队列为空')

  47.     def peek(self) -> Optional[int]:
  48.         """查看队列开头的元素,如果队列为空则返回None"""
  49.         if self.__len <= 0:
  50.             return self.__head.get_value()
  51.         return None

  52.     def empty(self) -> bool:
  53.         """返回队列是否为空"""
  54.         return self.__len == 0


  55. if __name__ == '__main__':
  56.     q = MyQueue()
  57.     for i in range(5):
  58.         q.push(i)
  59.     print(q.empty())
  60.     for i in range(5):
  61.         print(q.pop())
  62.     q.pop()  # 抛出异常
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2022-11-4 21:00:07 | 显示全部楼层
Brick_Porter 发表于 2022-10-21 21:24
类名有所修改,此外还使用了typing库中的Any和Optional这两个类来注释返回值类型。

还可以这么搞:
  1. class Myduilie:
  2.     def __init__(self):
  3.          self.duilie=[]
  4.     def push(self,x:int) -> None:
  5.          self.duilie.append(x)
  6.     def pop(self) -> int:
  7.           return self.duilie.pop(0)
  8.      def peek(self) -> int:
  9.           return self.duilie[0]
  10.       def empty() -> bool:
  11.           return not self.duilie

复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-17 08:47

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表