https://cloudstudying.kr/challenges/153
# 스택
class Stack():
def __init__(self):
self.stack = []
def __len__(self): # 스택 개수
return len(self.stack)
def push(self, data): # 추가
self.stack.append(data)
def pop(self): # 삭제
pop_object = None
if self.empty():
print("Stack is Empty")
else:
pop_object = self.stack.pop()
return pop_object
def empty(self): # 상태
is_empty = False
if len(self.stack) == 0:
is_empty = True
return is_empty
# 문제에서 주어진 수열
numbers = [4, 2, 0, 5, 6, 1, 3]
# 스택 생성
stack = Stack()
# 숫자 하나씩 스택 push
for i in numbers:
stack.push(i)
# 정렬된스택 새로 생성
sortedStack = Stack()
# 스택이 빌 때까지
while stack.empty() == False :
max = stack.pop() # 가장 위에있는 수를 최댓값으로 지정
arr = [] # 임시저장 리스트
for i in range(stack.__len__()) :
num = stack.pop() # 가장 위에 있는 숫자 pop
if num > max : # 최댓값보다 방금꺼낸 수가 더 크다면
arr.append(max) # 기존에 있던 최댓값은 리스트에 저장
max = num # 최댓값 변경
else :
arr.append(num) # 아니면 바로 리스트에 저장
sortedStack.push(max) # 모든 비교가 끝나면 최댓값 정렬스택에 push
for i in arr : # 임시저장 리스트에 있는 수를 다시 스택에 push
stack.push(arr[i])
# 출력
print("| |")
while sortedStack.empty() == False :
print(f"| {sortedStack.pop()} |\n")