我想通过使用堆栈数据结构而不使用递归来反转字符串
str= we defeated Corona
reversed str = anoroC detaefed ew
from collections import deque
class Stack:
def __init__(self):
self.container = deque()
def rev(self):
nstk= deque()
for i in self.container(len(self.container),0,-1):
nstk.append(i)
return nstk
def push(self,val):
self.container.append(val)
def peek(self):
return self.container
st = Stack()
lst= list('we defeated Corona')
st.push(lst)
print(st.peek())
revStack= st.rev()
print(revStack)
为什么我不能使用下面的代码来反转
def rev(self):
self.container.reverse()
普通列表和普通函数
如果您只需要实现一个堆栈,我认为没有理由使用
collections.deque
。我们可以很容易地构建一个简单的列表,[]
-使用堆栈很直观-
让它感觉更像python
如果您希望
stack
具有更面向对象的感觉,我们可以在普通函数周围添加一个接口-现在我们可以这样写
main
展开堆栈模块
继续向堆栈模块添加其他功能-
在面向对象的界面中包装新函数-
让我们验证一下
seek
和reverse
是否正常工作-相关阅读
在recent Q&A中,我展示了如何设计类似于上面
stack
的模块。如果您想了解随着程序的发展如何应用此技术,我鼓励您查看post:D持久堆栈
作为一个有趣的练习,我们可以在不使用
deque
、一个list
或任何其他内置数据容器的情况下实现堆栈。相反,我们将使用普通的None
和匿名函数。我分享这个例子是为了让你意识到程序员可以在他们的想象中构建任何东西,即使你使用的语言不包含特定的功能-每个堆栈操作都创建一个新的堆栈,而不是使用
.append
、.pop
或.reverse
修改底层堆栈。请注意,如果需要,我们可以unload
两次(或更多次)调用堆栈-就地修改与返回修改后的副本
假设您有一个名为“
CookieJar
”的容器类CookieJar
有一个名为insert()
的方法假设我们执行以下代码:
问题:
cj
是否与调用insert()
方法之前相同李>output
中究竟存储了什么李>在计算机编程中,有两种方法可以修改cookie jar的内容:
计算机程序员最常犯的错误之一是,他们假设一个变种人将返回一个修改过的容器副本
deque
类的reverse()
方法在适当的位置修改deques
。reverse()
输出None
计算机程序员对于他们选择使用哪种范式并不一致
来自
collections
库的deque
类的mutator方法修改了deque
的位置字符串类
str
的python mutator方法永远不要修改原始字符串相关问题 更多 >
编程相关推荐