Процесс список инструкций и вывести максимальное значение достигнуто


Входы выглядит так

b inc 5 if a > 1
a inc 1 if b < 5
c dec -10 if a >= 1
c inc -20 if c == 10

Меня беспокоит то, что мне нужно объявить __max__ как global (но не __registers__). Любые иные рекомендации на этот скрипт Python для новичка ?

import sys
import re

steps = 0

__registers__ = []
__max__ = None

class Instruction:
    def __init__(self, string):
        # Group 1 is the register name,
        # Group 2 is inc or dec,
        # Group 3 is the amount to increase or decrease,
        # Group 4 is the full condition
        # Group 5 is the name of register against which the condition is tested,
        # Group 6 is the operand of the condition,
        # Group 7 is the numerical value of the second term of the condition
        regex = "(\w+)\s(inc|dec)\s(-*\d+)\sif\s((\w+)\s([^\w\s]+)\s(-*\d+))"
        regex_string = re.search(regex, string)
        if regex_string:
            self.name = regex_string.group(1)
            __registers__.append(Register(self.name, 0))
            self.oper = regex_string.group(2)
            self.amount = int(regex_string.group(3))
            self.condition = regex_string.group(4)
            self.tested_register = regex_string.group(5)
            self.test_operand = regex_string.group(6)
            self.test_value = int(regex_string.group(7))

    def process_instruction(self):
        # We do the test : 
        p =  str(find(self.tested_register).value)
        condition = self.condition.replace(self.tested_register, p)
        if eval(condition):
            # We apply the inc / dec amount : 
            reg = find(self.name)
            # print(reg.value)
            if self.oper == "inc":
                reg.value = reg.value + self.amount
            else:
                reg.value = reg.value - self.amount
            # print(reg.value)
            global __max__
            if __max__ is None or reg.value > __max__:
                __max__ = reg.value

class Register:
    def __init__(self, name, value):
        self.name = name
        self.value = value

def find(register_name):
    for register in __registers__:
        if register.name == register_name:
            return register 

def get_max():
    max = None
    for regi in __registers__:
        if max is None or regi.value > max:
            max = regi.value
    return max

def main(arguments):
    fileName = sys.argv[1]
    global instructions
    instructions = [Instruction(line.rstrip('\n')) for line in open(fileName)]
    # print(__registers__)
    # print(len(__registers__))
    global __max__
    for instru in instructions:
        instru.process_instruction()
    print(get_max())
    print(__max__)


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))


Комментарии