首页 > 解决方案 > 如何通过给出范围并使用for循环在python中编写堆栈?

问题描述

我试图使用 python 3 和类编写堆栈操作,其中我不手动将元素添加到列表中,而是使用 0-10 的范围。但是我偶然发现了 l1 未定义或缺少参数的问题请帮助,下面是我用于推入空列表的代码。

class Stack():

    def __init__(self):
        self.l1 = []

    def push(self,l1):
        for i in range(0,10):
            self.ll.append(i)
            print(l1)

s = Stack(l1)
print("After stack push operation values are :", s.push())

标签: pythonpython-3.xclassfor-loopstack

解决方案


这是一本教科书的堆栈实现,给你一个参考:

1 class ArrayStack:
2 ”””LIFO Stack implementation using a Python list as underlying storage.”””
    3
    4 def init (self):
    5 ”””Create an empty stack.”””
    6    self.data = [ ] # nonpublic list instance
    7
    8 def len (self):
    9 ”””Return the number of elements in the stack.”””
    10    return len(self.data)
    11
    12 def is empty(self):
    13 ”””Return True if the stack is empty.”””
    14    return len(self.data) == 0
    15
    16 def push(self, e):
    17 ”””Add element e to the top of the stack.”””
    18    self.data.append(e) # new item stored at end of list
    19
    20 def top(self):
    21 ”””Return (but do not remove) the element at the top of the stack.
    22
    23 Raise Empty exception if the stack is empty.
    24 ”””
    25    if self.is empty( ):
    26       raise Empty( Stack is empty )
    27       return self.data[−1] # the last item in the list
    28
    29 def pop(self):
    30 ”””Remove and return the element from the top of the stack (i.e., LIFO).
    31
    32 Raise Empty exception if the stack is empty.
    33 ”””
    34    if self.isempty( ):
    35       raise Empty( Stack is empty )
    36    return self.data.pop( ) # remove last item from list

资料来源:Goodrich 等人的 Python 中的数据结构和算法

我认为您的示例还显示了一些关于如何使用类的错误。如果您想在初始化类时将参数传递给类,则需要像这样声明该参数:

class Stack:
    def __init__(self, arg1, arg2): # Declare args
        pass 

然后像这样调用:

s = Stack(arg1, arg2)

接下来,在方法定义中混合引用l1和。self.l1我还要补充一点,一个名为的变量l1容易出错,因为它看起来非常相似ll(我想我在你的帖子中发现了这样一个错字。我试图更正你的类定义,这就是我想出的:

class Stack():

    def __init__(self):
        self.l1 = []

    def push(self):
        for i in range(0,10):
            self.l1.append(i)
            print(self.l1)

s = Stack()
print("After stack push operation values are :", s.push())

请注意,这会导致:

[0]
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
After stack push operation values are : None

推荐阅读