from exceptions import Empty
class ArrayStack:
"""LIFO Stack implementation using a Python list as underlying storage."""
def __init__(self):
"""Create an empty stack."""
self._data = [] # nonpublic list instance
def __len__(self):
"""Return the number of elements in the stack."""
return len(self._data)
def is_empty(self):
"""Return True if the stack is empty."""
return len(self._data) == 0
def push(self, e):
"""Add element e to the top of the stack."""
self._data.append(e) # new item stored at end of list
def top(self):
"""Return (but do not remove) the element at the top of the stack.
Raise Empty exception if the stack is empty.
"""
if self.is_empty():
raise Empty('Stack is empty')
return self._data[-1] # the last item in the list
def pop(self):
"""Remove and return the element from the top of the stack (i.e., LIFO).
Raise Empty exception if the stack is empty.
"""
if self.is_empty():
raise Empty('Stack is empty')
return self._data.pop() # remove last item from list
L = ArrayStack()
file=open('C:/thisispython/testStack.txt','r')
while (1):
line=file.readline()
try:escape=line.index('\n')
except:escape=len(line)
if line:
L.push(line[0:escape])
else:
break
file.close()
위 클래스로 리스트 L을 정의했는데
print(L[3))이라고 하면 안돼는데 이유가 뭔가요?
몰라용
__getitem__ 특수 메서드를 구현 안하셨습니다
그런건 배운적이없는데 어디다가 쓰는건가요?
그리고 스택 인터페이스에서 직접 인덱스 접근은 미대상입니다
ArrayStack안에 구현해주셔야 함
자기 일은 스스로