Untitled

 avatar
unknown
python
4 years ago
1.9 kB
28
Indexable
class StackMaxEffective:
    def __init__(self):
        self.items = []
        self.max_history = []
        self.max = None

    def push(self, item):
        if not self.items:
            self.max = item
            self.max_history.append(item)
        elif self.max < item:
            self.max = item
            self.max_history.append(item)
        self.items.append(item)

    def pop(self):
        if not self.items:
            return 'error'
        removed = self.items.pop()
        if not self.items:
            self.max = None
        elif removed == self.max:
            self.max_history.pop(-1)
            index = len(self.max_history) - 1
            self.max = self.max_history[index]

    def get_max(self):
        return self.max


def result(num_of_commands, commands_list):
    i = 0
    stack = StackMaxEffective()
    while i < num_of_commands:
        if commands_list[i][0] == 'push':
            stack.push(commands_list[i][1])
        if commands_list[i][0] == 'pop':
            if not stack.items:
                print('error')
            else:
                stack.pop()
        if commands_list[i][0] == 'get_max':
            print(stack.max)
        i += 1


def file_reader(file_address):
    num_of_commands = 0
    commands_list = []
    i = 0
    with open(file_address, 'r') as reader:
        for line in reader.readlines():
            if i == 0:
                num_of_commands = int(line)
                i += 1
                continue
            line_ = line.strip().split(' ')
            if len(line_) > 1:
                commands_list.append([line_[0], int(line_[1])])
            else:
                commands_list.append([line_[0]])
    return num_of_commands, commands_list


if __name__ == '__main__':
    number_of_commands, commands = file_reader('input.txt')
    result(number_of_commands, commands)
Editor is loading...