2

I am trying to learn about stacks and found the following code on this website: http://interactivepython.org/runestone/static/pythonds/BasicDS/stacks.html

s = Stack()

s.push('a')
print(s.is_empty())
print(s.peek())
print(s.is_empty())
print(s.pop())
print(s.is_empty())

When running the code I get the error NameError: name 'Stack' is not defined. Can anyone help?

1
  • 6
    You need to import Stack from whatever module it is defined in. Commented May 4, 2015 at 0:14

3 Answers 3

3

As per another answer,

Stack is not built-in type in Python.

So, It has to define as there is not any library stated in interactive python tutorial.

I have taken Stack() class from interactive python tutorial and your code should be like this

class Stack:
     def __init__(self):
         self.items = []

     # I have changed method name isEmpty to is_empty
     # because in your code you have used is_empty
     def is_empty(self):
         return self.items == []

     def push(self, item):
         self.items.append(item)

     def pop(self):
         return self.items.pop()

     def peek(self):
         return self.items[len(self.items)-1]

     def size(self):
         return len(self.items)

s = Stack()
s.push('a')
print(s.is_empty())
print(s.peek())
print(s.is_empty())
print(s.pop())
print(s.is_empty())

Output:

False
a
False
a
True
Sign up to request clarification or add additional context in comments.

Comments

0

Stack is not a built-in type in python. You will need to define it first(or import from other module). In your case, you will need to run the ActiveCode 1 first.

Comments

0

Python lists actually behave like stacks: append() puts an item on top of the stack (it's like push() from other programming languages or other implementations, like the one you are referring to), whereas pop() can be used to retrieve the item from the top of the stack.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.