鱼C论坛

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

[已解决]39讲课后题用类模拟栈

[复制链接]
发表于 2020-9-8 20:13:20 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. class Stack:
  2.     def __init__(self,start=[]):
  3.         #能否直接用self.stack=start ?
  4.         self.stack=[]
  5.         for x in start:
  6.             self.push(x)

  7.     def isEmpty(self):
  8.         return not self.stack

  9.     def push(self,x):
  10.         self.stack.append(x)

  11.     def pop(self):
  12.         self.stack.pop()

  13.     def top(self):
  14.         print(self.stack[-1])

  15.     def bottom(self):
  16.         print(self.stack[0])

复制代码


想问下各位如果用self.stack=start 会有什么后患吗
最佳答案
2020-9-8 20:31:24
不可以用  self.stack=start 。因为这样写的话,stack和start 是同一个列表,若start被修改了那么栈也被修改了
举个例子
  1. class Stack:
  2.     def __init__(self,start=[]):
  3.         self.stack=start

  4.     def isEmpty(self):
  5.         return not self.stack

  6.     def push(self,x):
  7.         self.stack.append(x)

  8.     def pop(self):
  9.         self.stack.pop()

  10.     def top(self):
  11.         print(self.stack[-1])

  12.     def bottom(self):
  13.         print(self.stack[0])


  14. list1=[1,2,3,4]
  15. a=Stack(list1)
  16. a.top()  #这里得到的是4
  17. list1.pop()
  18. a.top()  #这里得到的是3
复制代码

但是可以用self.stack=start[:]



小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-9-8 20:31:24 | 显示全部楼层    本楼为最佳答案   
不可以用  self.stack=start 。因为这样写的话,stack和start 是同一个列表,若start被修改了那么栈也被修改了
举个例子
  1. class Stack:
  2.     def __init__(self,start=[]):
  3.         self.stack=start

  4.     def isEmpty(self):
  5.         return not self.stack

  6.     def push(self,x):
  7.         self.stack.append(x)

  8.     def pop(self):
  9.         self.stack.pop()

  10.     def top(self):
  11.         print(self.stack[-1])

  12.     def bottom(self):
  13.         print(self.stack[0])


  14. list1=[1,2,3,4]
  15. a=Stack(list1)
  16. a.top()  #这里得到的是4
  17. list1.pop()
  18. a.top()  #这里得到的是3
复制代码

但是可以用self.stack=start[:]



小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-9-8 21:44:21 | 显示全部楼层
sunrise085 发表于 2020-9-8 20:31
不可以用  self.stack=start 。因为这样写的话,stack和start 是同一个列表,若start被修改了那么栈也被修 ...

感谢 我片面了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-6-27 00:43

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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