gpt4 book ai didi

使用列表结构但不使用列表方法的Python堆栈模拟

转载 作者:太空宇宙 更新时间:2023-11-03 18:28:40 24 4
gpt4 key购买 nike

如果不使用列表方法,您将如何模拟堆栈的入栈和出栈函数?

到目前为止,我有类似的东西,但我不确定这是否有效:

stack = []

def Push(stack, element):
stack[len(stack)] = element

def Pop(stack):
element = tos
stack[len(stack) - 1] = None

return element;

会推送工作,以这种方式动态添加到列表中,并且 len 会适当更新吗?

对于 pop,如何在不使用任何列表函数的情况下从堆栈中“删除”?

最佳答案

您可以使用类似这样的内容(警告:这是一个幼稚的实现 - 它不会对传递的参数执行检查):

class Stack(object):
def __init__(self):
self._stack = [] # Allocate an empty list

def push(self, ele):
self._stack += [ele] # Use list concatenation to emulate the `push` operation

def pop(self):
last = self._stack[-1:] # Return the last element of the list (also works for empty lists)
self._stack = self.stack[0:-1] # Copy the elements from the beginning of the list to the last element of the list
return last # return the last element

# All stacks should have the `size` function to determine how many elements are
# in the stack:
def size(self):
return len(self._stack)

# Occasionally you'll want to see the contents of the stack, so we have to
# implement the `__str__` magic method:
def __str__(self):
return '[%s]' % ','.join(map(str, self._stack))

注意:此方法不使用任何 list 方法,例如 appendpop

示例:

s = Stack()

# fill the stack with values:
for i in xrange(10):
s.push(i+1)

print s # Outputs: [1,2,3,4,5,6,7,8,9,10]

s.pop()
s.pop()

print s # Outputs: [1,2,3,4,5,6,7,8]

关于使用列表结构但不使用列表方法的Python堆栈模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22751115/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com