Run an accumulator machine

Simulate a tiny accumulator machine through its fetch-decode-execute cycle. It has one register, ACC, a program counter starting at 0, and 100 memory cells (addresses 0 to 99), all starting at 0. Instructions are numbered from 0.

InstructionMeaning
LOADI vACC = v (v may be negative)
LOAD aACC = memory[a]
STORE amemory[a] = ACC
ADD a, SUB aACC = ACC + memory[a], ACC = ACC − memory[a]
JMP ncontinue at instruction n
JZ nif ACC is 0, continue at instruction n
OUTprint ACC
HALTstop

The machine also stops when it moves past the last instruction. Every test program stops within 1000 instructions.

Input

A line with n (1 ≤ n ≤ 100), then n instructions, one per line.

Output

One line for each OUT.

Examples

Example 1 · Input
8
LOADI 10
STORE 0
LOADI 20
ADD 0
STORE 0
LOADI 30
ADD 0
OUT
Expected output
60
Example 2 · Input
11
LOADI 1
STORE 1
LOADI 3
STORE 0
LOAD 0
JZ 10
OUT
SUB 1
STORE 0
JMP 4
HALT
Expected output
3
2
1

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Keep pc = 0, acc = 0 and memory = [0] * 100.

Hint 2

Loop: if pc is past the last instruction, stop; otherwise fetch program[pc], add 1 to pc, then carry out the instruction.

Hint 3

JMP sets pc; JZ sets pc only when acc == 0; OUT prints acc; HALT stops.

Solution

Show one correct solution (try it yourself first)
n = int(input())
program = [input().split() for _ in range(n)]
memory = [0] * 100
pc, acc = 0, 0
while pc < len(program):
    parts = program[pc]
    pc += 1
    op = parts[0]
    arg = int(parts[1]) if len(parts) > 1 else 0
    if op == "LOADI":
        acc = arg
    elif op == "LOAD":
        acc = memory[arg]
    elif op == "STORE":
        memory[arg] = acc
    elif op == "ADD":
        acc += memory[arg]
    elif op == "SUB":
        acc -= memory[arg]
    elif op == "JMP":
        pc = arg
    elif op == "JZ":
        if acc == 0:
            pc = arg
    elif op == "OUT":
        print(acc)
    elif op == "HALT":
        break

Lesson: The fetch–decode–execute cycle →