design stacks using array solution - #2439
Conversation
|
The student has implemented a basic stack using an array (Python list) with the standard operations: Strengths:
Issues and Areas for Improvement:
Suggested Refactor: class myStack:
def __init__(self):
self.stack = []
def isEmpty(self):
return len(self.stack) == 0
def push(self, item):
self.stack.append(item)
def size(self):
return len(self.stack)
def pop(self):
if self.isEmpty():
raise IndexError("pop from empty stack")
return self.stack.pop()
def peek(self):
if self.isEmpty():
raise IndexError("peek from empty stack")
return self.stack[-1]
def show(self):
print(self.stack)This refactor is cleaner, more Pythonic, and avoids the pitfalls of manual index tracking. |
precoruse 1 problem 1