Стек должен иметь фиксированную емкость в 25 ходов, а правила перемещения следующие:
- Двигаться вперед → толкать (направление) → +10 баллов
- Тупик → pop() → –5 баллов
- Текущая позиция → просмотр/наверх
- Попытаться нажать, когда стек полон → переполнение (–20 баллов)
- Попробовать всплывающее окно, когда стек пуст → переполнение
- Достигнут выход → +50 очков
Код: Выделить всё
push("Left")
push("Right")
pop() # dead-end
push("Forward")
push("Left")
push(...) # beyond stack capacity → test overflow
pop repeatedly # return to start
- Реализация стека с использованием списка Python (без встроенных библиотек стека)
- Обработка переполнения, потери значения и оценки
- Печать содержимого стека и оценки после каждого move
Я начал определять класс стека, но не уверен, как правильно применять условия оценки и условия заполнения/пустоты.
Код: Выделить всё
class Stack:
def __init__(self, capacity=25):
self.items = []
self.capacity = capacity
self.score = 0
def push(self, direction):
# I am not sure how to handle scoring and overflow here
if len(self.items) < self.capacity:
self.items.append(direction)
# self.score += 10 → not sure if this is correct
else:
# Should I use return, print, or raise error here?
# self.score -= 20
pass
def pop(self):
# Confused about underflow and scoring
if len(self.items) > 0:
direction = self.items.pop()
# self.score -= 5
return direction
else:
# Stack is empty → underflow
return None
def peek(self):
if len(self.items) > 0:
return self.items[-1]
return None # not sure if this is correct
# Not sure how to simulate the movement sequence correctly
maze_moves = ["Left", "Right", "dead-end", "Forward", "Left"]
# I want to simulate push/pop based on this list, but confused on logic
stack = Stack()
for move in maze_moves:
if move == "dead-end":
stack.pop()
else:
stack.push(move)
print(stack.items, stack.score)
Предпочитаемый язык: Python
Спасибо!
Подробнее здесь: https://stackoverflow.com/questions/798 ... d-capacity
Мобильная версия