-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStacks.py
More file actions
64 lines (59 loc) · 1.98 KB
/
Copy pathStacks.py
File metadata and controls
64 lines (59 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# A Stack is a type of list where instead of accessing
# any item in the list at any time, you can only add
# or remove items from the top of the Stack.
#
# Adding a new item to the stack is called "pushing"
# the item onto the stack. Removing the top item on
# the stack is called "popping" the item off the stack.
# When an item is "popped" off the stack, it is removed
# from the list altogether.
#
# Write a class called Stack. Stack should have the
# following methods:
#
# - An __init__ method that initializes the empty list
# that is the stack's contents.
# - A stack_push() method that takes one parameter (in
# addition to self): an item to push onto the top
# of the stack.
# - A stack_pop() method that returns the current top
# item on the stack and removes it from the underlying
# list. If the list is already empty, this returns
# None.
#
# For example, the following code would print the
# numbers 3, 2, and 1 (in that order). Note that this
# is the opposite order of how they are pushed: the
# pop method will always return the elements in the
# reverse order that they were added in.
#
# new_stack = Stack()
# new_stack.stack_push(1)
# new_stack.stack_push(2)
# new_stack.stack_push(3)
# print(new_stack.stack_pop())
# print(new_stack.stack_pop())
# print(new_stack.stack_pop())
# Add your class here!
class Stack:
def __init__(self):
self.items = []
def stack_push(self, num):
self.items.append(num)
def stack_pop(self):
if len(self.items) == 0:
return None
else:
n = self.items[-1]
del self.items[-1]
return n
# The following lines of code will test your class.
# If it works correctly, it will print 3, 2, and 1
# in that order, each on their own line.
new_stack = Stack()
new_stack.stack_push(1)
new_stack.stack_push(2)
new_stack.stack_push(3)
print(new_stack.stack_pop())
print(new_stack.stack_pop())
print(new_stack.stack_pop())