Here is the description of a new assembly language: * 8 registers (R1, R2, R3, R4, R5, R6, R7, R8) that can hold integers. * 1 flag that can hold a boolean value (True or False). * 100 memory addresses (0-99) that can hold integers. * 1 instruction pointer that points to the current instruction being executed. Each instruction is of the form OP ARG1 ARG2 ... where ARGn can be either a register (e.g., R1) or a constant (e.g., 10). Labels are written with a lowercase word followed by colon. The assembly language supports the following instructions: * SET Rx C: Assigns the value C to register Rx. * ADD Rx Ry Rz: Adds the values of Ry and Rz and stores the result in Rx. * (similarly for SUB, MUL, DIV, MOD) * EQ Rx Ry: Sets the flag to True if Rx and Ry are equal, False otherwise. * (similarly for NEQ, LT (Rx < Ry), LTE, GT, GTE) * INC/DEC Rx: Increments/Decrements the value of Rx by one. * JMP L: Jumps to label L unconditionally. * JT/JF (jump if true / jump if false) L: Jumps to label L if the is set or not set. * LOAD Rx M: Loads the value at memory address M into register Rx. * STORE Rx M: Stores the value of register Rx into memory address M. * HCF: Stops the program (with pizzazz) For example here is a program to compute the first 20 square numbers (1, 4, 9, 16, 25, ...): SET R1 0 // Counter for storing squares SET R2 1 // Number to square loop: MUL R3 R2 R2 // R3 = R2 * R2 STORE R3 R1 // Store R3 at address R1 INC R1 // Increment address INC R2 // Increment number SET R3 20 EQ R1 R3 // Check if 20 squares are found JF loop // If not 20 squares found yet, continue finding end: HCF // Stop program Write me a python interpreter `evaluate(str)` that returns the resulting memory state after running the program. For example, `evaluate(program)` should return `[1, 4, 9, 16, 25, ...]` for the above program.
Here is the description of a new assembly language: * 8 registers (R1, R2, R3, R4, R5, R6, R7, R8) that can hold integers. * 1 flag that can hold a boolean value (True or False). * 100 memory addresses (0-99) that can hold integers. * 1 instruction pointer that points to the current instruction being executed. Each instruction is of the form OP ARG1 ARG2 ... where ARGn can be either a register (e.g., R1) or a constant (e.g., 10). Labels are written with a lowercase word followed by colon. The assembly language supports the following instructions: * SET Rx C: Assigns the value C to register Rx. * ADD Rx Ry Rz: Adds the values of Ry and Rz and stores the result in Rx. * (similarly for SUB, MUL, DIV, MOD) * EQ Rx Ry: Sets the flag to True if Rx and Ry are equal, False otherwise. * (similarly for NEQ, LT (Rx < Ry), LTE, GT, GTE) * INC/DEC Rx: Increments/Decrements the value of Rx by one. * JMP L: Jumps to label L unconditionally. * JT/JF (jump if true / jump if false) L: Jumps to label L if the is set or not set. * LOAD Rx M: Loads the value at memory address M into register Rx. * STORE Rx M: Stores the value of register Rx into memory address M. * HCF: Stops the program (with pizzazz) For example here is a program to compute the first 20 square numbers (1, 4, 9, 16, 25, ...): SET R1 0 // Counter for storing squares SET R2 1 // Number to square loop: MUL R3 R2 R2 // R3 = R2 * R2 STORE R3 R1 // Store R3 at address R1 INC R1 // Increment address INC R2 // Increment number SET R3 20 EQ R1 R3 // Check if 20 squares are found JF loop // If not 20 squares found yet, continue finding end: HCF // Stop program Write me a python interpreter `evaluate(str)` that returns the resulting memory state after running the program. For example, `evaluate(program)` should return `[1, 4, 9, 16, 25, ...]` for the above program.
Below is one acceptable solution. For example, you could write: ------------------------------------------------ def evaluate(program): # Define our machine state: # 8 registers (R1 .. R8) all starting at 0 regs = {f"R{i}": 0 for i in range(1, 9)} flag = False memory = [0] * 100 # We'll accumulate our instructions in a list. # Also, we need a dictionary mapping labels (without colon) to instruction indices. instructions = [] labels = {} # First, preprocess the program: # - Remove comments (anything after //) # - Strip whitespace, skip empty lines. # - Record label definitions (lines ending with ':') and instructions. lines = program.splitlines() line_idx = 0 # count line in our instructions list (excluding labels) for raw_line in lines: # Remove comments line = raw_line.split("//")[0].strip() if not line: continue # Check for label (ends with a colon and no further tokens before a comment) if line.endswith(':'): lbl = line[:-1].strip() if lbl: labels[lbl] = line_idx continue # Otherwise it's an instruction. Append it. instructions.append(line) line_idx += 1 # Helper function: return the integer value of an argument, # if the argument is a register name (R1...R8) then return its value # otherwise, convert to int. def get_val(arg): if arg in regs: return regs[arg] try: return int(arg) except ValueError: raise ValueError(f"Invalid argument {arg}") # Execution: ip = 0 while ip < len(instructions): # Fetch the instruction and split into tokens tokens = instructions[ip].split() op = tokens[0] args = tokens[1:] # For most instructions, after executing, if we have not jumped, we do ip += 1. advanced = True if op == "HCF": break elif op == "SET": # SET Rx C # First argument must be a register; second a number. reg = args[0] val = get_val(args[1]) regs[reg] = val elif op in ("ADD", "SUB", "MUL", "DIV", "MOD"): # Instruction form: OP Rx ARG1 ARG2. dest = args[0] arg1 = get_val(args[1]) arg2 = get_val(args[2]) if op == "ADD": regs[dest] = arg1 + arg2 elif op == "SUB": regs[dest] = arg1 - arg2 elif op == "MUL": regs[dest] = arg1 * arg2 elif op == "DIV": # integer division; assume division by zero does not occur. regs[dest] = arg1 // arg2 elif op == "MOD": regs[dest] = arg1 % arg2 elif op in ("EQ", "NEQ", "LT", "LTE", "GT", "GTE"): # Compare two args. They can be register or constant. a = get_val(args[0]) b = get_val(args[1]) if op == "EQ": flag = (a == b) elif op == "NEQ": flag = (a != b) elif op == "LT": flag = (a < b) elif op == "LTE": flag = (a <= b) elif op == "GT": flag = (a > b) elif op == "GTE": flag = (a >= b) elif op == "INC": # INC Rx: Increment register Rx by one r = args[0] regs[r] += 1 elif op == "DEC": # DEC Rx: Decrement register Rx by one r = args[0] regs[r] -= 1 elif op == "JMP": # Unconditional jump. The jump argument is assumed to be a label. lbl = args[0] if lbl not in labels: raise ValueError(f"Label '{lbl}' not defined") ip = labels[lbl] advanced = False elif op == "JT": # Jump if flag is true. lbl = args[0] if flag: if lbl not in labels: raise ValueError(f"Label '{lbl}' not defined") ip = labels[lbl] advanced = False elif op == "JF": # Jump if flag is false. lbl = args[0] if not flag: if lbl not in labels: raise ValueError(f"Label '{lbl}' not defined") ip = labels[lbl] advanced = False elif op == "LOAD": # LOAD Rx M reg = args[0] # M may be a register or a constant: addr = get_val(args[1]) if addr < 0 or addr >= len(memory): raise ValueError(f"Invalid memory address {addr}") regs[reg] = memory[addr] elif op == "STORE": # STORE Rx M reg = args[0] addr = get_val(args[1]) if addr < 0 or addr >= len(memory): raise ValueError(f"Invalid memory address {addr}") memory[addr] = regs[reg] else: raise ValueError(f"Unknown operation: {op}") if advanced: ip += 1 return memory # For testing, using the sample program that calculates the first 20 square numbers: program = """ SET R1 0 // Counter for storing squares SET R2 1 // Number to square loop: MUL R3 R2 R2 // R3 = R2 * R2 STORE R3 R1 // Store R3 at address R1 INC R1 // Increment address INC R2 // Increment number SET R3 20 EQ R1 R3 // Check if 20 squares are found JF loop // If not 20 squares found yet, continue finding end: HCF // Stop program """ if __name__ == '__main__': result_memory = evaluate(program) # We expect the first 20 addresses to have square numbers: print(result_memory[:20]) ------------------------------------------------ Explanation: 1. We create dictionaries for registers (R1–R8) and a list for the 100 memory addresses. 2. We preprocess the given program, stripping comments and whitespace and collecting labels with their corresponding instruction index. 3. We define a helper function get_val(arg) that returns the value from a register if the argument is, for example, "R2". Otherwise it converts the constant to an integer. 4. In the execution loop we parse each instruction and update the machine state. For conditional and unconditional jumps the instruction pointer is adjusted directly. 5. The program stops when HCF is encountered. 6. After execution, the function returns the memory state. When you run the interpreter with the sample program (which fills memory addresses 0–19 with the square numbers 1, 4, 9, …, 400), evaluate(program) returns the memory list. This solution meets the requirements.
I extracted the following code from that output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 | #!/usr/bin/env python3 def evaluate(program): # Define our machine state: # 8 registers (R1 .. R8) all starting at 0 regs = {f"R{i}": 0 for i in range(1, 9)} flag = False memory = [0] * 100 # We'll accumulate our instructions in a list. # Also, we need a dictionary mapping labels (without colon) to instruction indices. instructions = [] labels = {} # First, preprocess the program: # - Remove comments (anything after //) # - Strip whitespace, skip empty lines. # - Record label definitions (lines ending with ':') and instructions. lines = program.splitlines() line_idx = 0 # count line in our instructions list (excluding labels) for raw_line in lines: # Remove comments line = raw_line.split("//")[0].strip() if not line: continue # Check for label (ends with a colon and no further tokens before a comment) if line.endswith(':'): lbl = line[:-1].strip() if lbl: labels[lbl] = line_idx continue # Otherwise it's an instruction. Append it. instructions.append(line) line_idx += 1 # Helper function: return the integer value of an argument, # if the argument is a register name (R1...R8) then return its value # otherwise, convert to int. def get_val(arg): if arg in regs: return regs[arg] try: return int(arg) except ValueError: raise ValueError(f"Invalid argument {arg}") # Execution: ip = 0 while ip < len(instructions): # Fetch the instruction and split into tokens tokens = instructions[ip].split() op = tokens[0] args = tokens[1:] # For most instructions, after executing, if we have not jumped, we do ip += 1. advanced = True if op == "HCF": break elif op == "SET": # SET Rx C # First argument must be a register; second a number. reg = args[0] val = get_val(args[1]) regs[reg] = val elif op in ("ADD", "SUB", "MUL", "DIV", "MOD"): # Instruction form: OP Rx ARG1 ARG2. dest = args[0] arg1 = get_val(args[1]) arg2 = get_val(args[2]) if op == "ADD": regs[dest] = arg1 + arg2 elif op == "SUB": regs[dest] = arg1 - arg2 elif op == "MUL": regs[dest] = arg1 * arg2 elif op == "DIV": # integer division; assume division by zero does not occur. regs[dest] = arg1 // arg2 elif op == "MOD": regs[dest] = arg1 % arg2 elif op in ("EQ", "NEQ", "LT", "LTE", "GT", "GTE"): # Compare two args. They can be register or constant. a = get_val(args[0]) b = get_val(args[1]) if op == "EQ": flag = (a == b) elif op == "NEQ": flag = (a != b) elif op == "LT": flag = (a < b) elif op == "LTE": flag = (a <= b) elif op == "GT": flag = (a > b) elif op == "GTE": flag = (a >= b) elif op == "INC": # INC Rx: Increment register Rx by one r = args[0] regs[r] += 1 elif op == "DEC": # DEC Rx: Decrement register Rx by one r = args[0] regs[r] -= 1 elif op == "JMP": # Unconditional jump. The jump argument is assumed to be a label. lbl = args[0] if lbl not in labels: raise ValueError(f"Label '{lbl}' not defined") ip = labels[lbl] advanced = False elif op == "JT": # Jump if flag is true. lbl = args[0] if flag: if lbl not in labels: raise ValueError(f"Label '{lbl}' not defined") ip = labels[lbl] advanced = False elif op == "JF": # Jump if flag is false. lbl = args[0] if not flag: if lbl not in labels: raise ValueError(f"Label '{lbl}' not defined") ip = labels[lbl] advanced = False elif op == "LOAD": # LOAD Rx M reg = args[0] # M may be a register or a constant: addr = get_val(args[1]) if addr < 0 or addr >= len(memory): raise ValueError(f"Invalid memory address {addr}") regs[reg] = memory[addr] elif op == "STORE": # STORE Rx M reg = args[0] addr = get_val(args[1]) if addr < 0 or addr >= len(memory): raise ValueError(f"Invalid memory address {addr}") memory[addr] = regs[reg] else: raise ValueError(f"Unknown operation: {op}") if advanced: ip += 1 return memory |
Running the following program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 | #!/usr/bin/env python3 def evaluate(program): # Define our machine state: # 8 registers (R1 .. R8) all starting at 0 regs = {f"R{i}": 0 for i in range(1, 9)} flag = False memory = [0] * 100 # We'll accumulate our instructions in a list. # Also, we need a dictionary mapping labels (without colon) to instruction indices. instructions = [] labels = {} # First, preprocess the program: # - Remove comments (anything after //) # - Strip whitespace, skip empty lines. # - Record label definitions (lines ending with ':') and instructions. lines = program.splitlines() line_idx = 0 # count line in our instructions list (excluding labels) for raw_line in lines: # Remove comments line = raw_line.split("//")[0].strip() if not line: continue # Check for label (ends with a colon and no further tokens before a comment) if line.endswith(':'): lbl = line[:-1].strip() if lbl: labels[lbl] = line_idx continue # Otherwise it's an instruction. Append it. instructions.append(line) line_idx += 1 # Helper function: return the integer value of an argument, # if the argument is a register name (R1...R8) then return its value # otherwise, convert to int. def get_val(arg): if arg in regs: return regs[arg] try: return int(arg) except ValueError: raise ValueError(f"Invalid argument {arg}") # Execution: ip = 0 while ip < len(instructions): # Fetch the instruction and split into tokens tokens = instructions[ip].split() op = tokens[0] args = tokens[1:] # For most instructions, after executing, if we have not jumped, we do ip += 1. advanced = True if op == "HCF": break elif op == "SET": # SET Rx C # First argument must be a register; second a number. reg = args[0] val = get_val(args[1]) regs[reg] = val elif op in ("ADD", "SUB", "MUL", "DIV", "MOD"): # Instruction form: OP Rx ARG1 ARG2. dest = args[0] arg1 = get_val(args[1]) arg2 = get_val(args[2]) if op == "ADD": regs[dest] = arg1 + arg2 elif op == "SUB": regs[dest] = arg1 - arg2 elif op == "MUL": regs[dest] = arg1 * arg2 elif op == "DIV": # integer division; assume division by zero does not occur. regs[dest] = arg1 // arg2 elif op == "MOD": regs[dest] = arg1 % arg2 elif op in ("EQ", "NEQ", "LT", "LTE", "GT", "GTE"): # Compare two args. They can be register or constant. a = get_val(args[0]) b = get_val(args[1]) if op == "EQ": flag = (a == b) elif op == "NEQ": flag = (a != b) elif op == "LT": flag = (a < b) elif op == "LTE": flag = (a <= b) elif op == "GT": flag = (a > b) elif op == "GTE": flag = (a >= b) elif op == "INC": # INC Rx: Increment register Rx by one r = args[0] regs[r] += 1 elif op == "DEC": # DEC Rx: Decrement register Rx by one r = args[0] regs[r] -= 1 elif op == "JMP": # Unconditional jump. The jump argument is assumed to be a label. lbl = args[0] if lbl not in labels: raise ValueError(f"Label '{lbl}' not defined") ip = labels[lbl] advanced = False elif op == "JT": # Jump if flag is true. lbl = args[0] if flag: if lbl not in labels: raise ValueError(f"Label '{lbl}' not defined") ip = labels[lbl] advanced = False elif op == "JF": # Jump if flag is false. lbl = args[0] if not flag: if lbl not in labels: raise ValueError(f"Label '{lbl}' not defined") ip = labels[lbl] advanced = False elif op == "LOAD": # LOAD Rx M reg = args[0] # M may be a register or a constant: addr = get_val(args[1]) if addr < 0 or addr >= len(memory): raise ValueError(f"Invalid memory address {addr}") regs[reg] = memory[addr] elif op == "STORE": # STORE Rx M reg = args[0] addr = get_val(args[1]) if addr < 0 or addr >= len(memory): raise ValueError(f"Invalid memory address {addr}") memory[addr] = regs[reg] else: raise ValueError(f"Unknown operation: {op}") if advanced: ip += 1 return memory answer = evaluate(""" SET R1 0 SET R2 1 loop: MUL R3 R2 R2 STORE R3 R1 INC R1 INC R2 SET R3 20 EQ R1 R3 JF loop """)[:10] expected = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] assert answer == expected, f'Wrong answer; got {answer} instead of {expected}' answer = evaluate(""" SET R1 2 // Starting number to check for prime start_find_primes: JMP is_prime // Control will return after executing is_prime with R1 as input and R2 containing the result ready_prime: SET R7 1 EQ R2 R7 // Check if R2 is 1 (prime) JF increment // If not prime, skip storing and increment the number // Store prime number in memory and increment count STORE R1 R8 // Store prime number at address pointed by R8 INC R8 // Increment prime count // Check if 100 primes are found SET R7 100 EQ R8 R7 JF increment // If not 100 primes found yet, continue finding JMP end // If 100 primes found, end program increment: INC R1 // Increment number to check for prime JMP start_find_primes // Check next number is_prime: SET R2 1 // Assume number is prime initially SET R3 2 // Start divisor from 2 start_loop: // Label to start the loop // Check if we have exceeded the square root of R1 MUL R4 R3 R3 // R4 = R3 * R3 GT R4 R1 // Set flag if R4 > R1 JT is_prime_end // If not exceeded, continue; else, end loop MOD R6 R1 R3 // R6 = R1 % R3 SET R7 0 EQ R7 R6 // Check if R6 is 0 JT not_prime // If yes, number is not prime INC R3 // Increment divisor JMP start_loop // Repeat loop not_prime: SET R2 0 // Set result to 0 (not prime) is_prime_end: JMP ready_prime end: """)[:10] expected = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] assert answer == expected, f'Wrong answer; got {answer} instead of {expected}' print('All tests passed') |
All tests passed
Testing if the previous output contains the string All tests passed
: True
Here is the description of a new assembly language: * 8 registers (R1, R2, R3, R4, R5, R6, R7, R8) that can hold integers. * 1 flag that can hold a boolean value (True or False). * 100 memory addresses (0-99) that can hold integers. * 1 instruction pointer that points to the current instruction being executed. Each instruction is of the form OP ARG1 ARG2 ... where ARGn can be either a register (e.g., R1) or a constant (e.g., 10). Labels are written with a lowercase word followed by colon. The assembly language supports the following instructions: * SET Rx C: Assigns the value C to register Rx. * ADD Rx Ry Rz: Adds the values of Ry and Rz and stores the result in Rx. * (similarly for SUB, MUL, DIV, MOD) * EQ Rx Ry: Sets the flag to True if Rx and Ry are equal, False otherwise. * (similarly for NEQ, LT (Rx < Ry), LTE, GT, GTE) * INC/DEC Rx: Increments/Decrements the value of Rx by one. * JMP L: Jumps to label L unconditionally. * JT/JF (jump if true / jump if false) L: Jumps to label L if the is set or not set. * LOAD Rx M: Loads the value at memory address M into register Rx. * STORE Rx M: Stores the value of register Rx into memory address M. * HCF: Stops the program (with pizzazz) For example here is a program to compute the first 20 square numbers (1, 4, 9, 16, 25, ...): SET R1 0 // Counter for storing squares SET R2 1 // Number to square loop: MUL R3 R2 R2 // R3 = R2 * R2 STORE R3 R1 // Store R3 at address R1 INC R1 // Increment address INC R2 // Increment number SET R3 20 EQ R1 R3 // Check if 20 squares are found JF loop // If not 20 squares found yet, continue finding end: HCF // Stop program Write me a python interpreter `evaluate(str)` that returns the resulting memory state after running the program. For example, `evaluate(program)` should return `[1, 4, 9, 16, 25, ...]` for the above program.
Here is the description of a new assembly language: * 8 registers (R1, R2, R3, R4, R5, R6, R7, R8) that can hold integers. * 1 flag that can hold a boolean value (True or False). * 100 memory addresses (0-99) that can hold integers. * 1 instruction pointer that points to the current instruction being executed. Each instruction is of the form OP ARG1 ARG2 ... where ARGn can be either a register (e.g., R1) or a constant (e.g., 10). Labels are written with a lowercase word followed by colon. The assembly language supports the following instructions: * SET Rx C: Assigns the value C to register Rx. * ADD Rx Ry Rz: Adds the values of Ry and Rz and stores the result in Rx. * (similarly for SUB, MUL, DIV, MOD) * EQ Rx Ry: Sets the flag to True if Rx and Ry are equal, False otherwise. * (similarly for NEQ, LT (Rx < Ry), LTE, GT, GTE) * INC/DEC Rx: Increments/Decrements the value of Rx by one. * JMP L: Jumps to label L unconditionally. * JT/JF (jump if true / jump if false) L: Jumps to label L if the is set or not set. * LOAD Rx M: Loads the value at memory address M into register Rx. * STORE Rx M: Stores the value of register Rx into memory address M. * HCF: Stops the program (with pizzazz) For example here is a program to compute the first 20 square numbers (1, 4, 9, 16, 25, ...): SET R1 0 // Counter for storing squares SET R2 1 // Number to square loop: MUL R3 R2 R2 // R3 = R2 * R2 STORE R3 R1 // Store R3 at address R1 INC R1 // Increment address INC R2 // Increment number SET R3 20 EQ R1 R3 // Check if 20 squares are found JF loop // If not 20 squares found yet, continue finding end: HCF // Stop program Write me a python interpreter `evaluate(str)` that returns the resulting memory state after running the program. For example, `evaluate(program)` should return `[1, 4, 9, 16, 25, ...]` for the above program.
Below is one complete solution in Python. For example, you can copy‐paste the code into a Python file and then call evaluate(program) (where program is a string containing your assembly code) to get the 100–element memory list at the time the program halted. Below is the full code: ------------------------------------------------ def evaluate(program: str): # Initialize state registers = {"R" + str(i): 0 for i in range(1, 9)} flag = False memory = [0] * 100 ip = 0 # instruction pointer # First, split the program into lines and remove comments/whitespace. lines = program.splitlines() # We will build two lists: one for instructions (each as a list of tokens), # and a label mapping: label_name -> index into instructions list. instructions = [] labels = {} # mapping from label: name -> instruction index # Preprocessing: for line in lines: # Remove inline comments - assume comments start with // line = line.split("//")[0] line = line.strip() if not line: continue # Check if the line is a label (or label plus instruction) # A label is a lowercase word ending in colon. # We allow labels to appear on their own or before an instruction. tokens = line.split() while tokens and tokens[0].endswith(":"): lab = tokens[0][:-1] # remove colon labels[lab] = len(instructions) tokens = tokens[1:] if tokens: instructions.append(tokens) # Helper: function to resolve an argument token to integer value. # It can be either a register like 'R1' or a number (constant). def get_value(token): if token.startswith("R"): return registers[token] else: return int(token) # Now run the program. while ip < len(instructions): inst = instructions[ip] op = inst[0] # For debugging, you could print(ip, inst) if op == "HCF": break elif op == "SET": # SET Rx C: load constant C into register Rx. # (We assume that the constant is provided even if it might be interpreted as register name) reg = inst[1] # Assuming second argument is always a constant. # But if it is a register, we could allow that too: try: registers[reg] = int(inst[2]) except ValueError: # treat it as register value if not an int literal registers[reg] = registers[inst[2]] ip += 1 elif op in ("ADD", "SUB", "MUL", "DIV", "MOD"): # These instructions all have the form: op Rx Ry Rz dest, src1, src2 = inst[1], inst[2], inst[3] a = get_value(src1) b = get_value(src2) if op == "ADD": registers[dest] = a + b elif op == "SUB": registers[dest] = a - b elif op == "MUL": registers[dest] = a * b elif op == "DIV": # Assume integer division. (Division by zero would raise an error.) registers[dest] = a // b elif op == "MOD": registers[dest] = a % b ip += 1 elif op in ("EQ", "NEQ", "LT", "LTE", "GT", "GTE"): # All of these take two register operands (or two arguments that evaluate to ints) a = get_value(inst[1]) b = get_value(inst[2]) if op == "EQ": flag = (a == b) elif op == "NEQ": flag = (a != b) elif op == "LT": flag = (a < b) elif op == "LTE": flag = (a <= b) elif op == "GT": flag = (a > b) elif op == "GTE": flag = (a >= b) ip += 1 elif op == "INC": # INC Rx: increment register by one. r = inst[1] registers[r] += 1 ip += 1 elif op == "DEC": r = inst[1] registers[r] -= 1 ip += 1 elif op == "JMP": # JMP L: unconditional jump label = inst[1] if label not in labels: raise ValueError("Label '%s' not found" % label) ip = labels[label] elif op == "JT": # Jump if flag is True label = inst[1] if flag: if label not in labels: raise ValueError("Label '%s' not found" % label) ip = labels[label] else: ip += 1 elif op == "JF": # Jump if flag is False label = inst[1] if not flag: if label not in labels: raise ValueError("Label '%s' not found" % label) ip = labels[label] else: ip += 1 elif op == "LOAD": # LOAD Rx M: load memory at address M into register. reg = inst[1] addr = get_value(inst[2]) # Ensure address is in range: if not (0 <= addr < len(memory)): raise IndexError("Memory address %d out of range" % addr) registers[reg] = memory[addr] ip += 1 elif op == "STORE": # STORE Rx M: store register value into memory at address M. reg = inst[1] addr = get_value(inst[2]) if not (0 <= addr < len(memory)): raise IndexError("Memory address %d out of range" % addr) memory[addr] = registers[reg] ip += 1 else: raise ValueError("Unknown instruction: %s" % op) return memory # Example usage: if __name__ == "__main__": # Program to compute the first 20 square numbers as given in the description. program = """ SET R1 0 // Counter for storing squares SET R2 1 // Number to square loop: MUL R3 R2 R2 // R3 = R2 * R2 STORE R3 R1 // Store R3 at address R1 INC R1 // Increment address INC R2 // Increment number SET R3 20 EQ R1 R3 // Check if 20 squares are found JF loop // If not 20 squares found yet, continue finding end: HCF // Stop program """ mem = evaluate(program) # Print stored squares (should be the first 20 squares) squares = [mem[i] for i in range(20)] print(squares) ------------------------------------------------ Explanation: 1. The code splits the input into lines and removes inline comments (anything after "//"). 2. It detects labels (words ending in “:”) and maps them to the index in the instructions list (so that jumps work correctly). 3. The interpreter then iterates through each instruction using the instruction pointer (ip). Depending on the opcode (e.g., SET, ADD, EQ, INC, JMP, etc.) it executes the matching operation. 4. When the HCF instruction is encountered (or ip goes past the list), the program stops. 5. Finally, the memory list (a list of 100 integers) is returned. Running the sample program produces the first twenty square numbers stored in the beginning of memory.
I extracted the following code from that output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 | from typing import List def evaluate(program: str): # Initialize state registers = {"R" + str(i): 0 for i in range(1, 9)} flag = False memory = [0] * 100 ip = 0 # instruction pointer # First, split the program into lines and remove comments/whitespace. lines = program.splitlines() # We will build two lists: one for instructions (each as a list of tokens), # and a label mapping: label_name -> index into instructions list. instructions = [] labels = {} # mapping from label: name -> instruction index # Preprocessing: for line in lines: # Remove inline comments - assume comments start with // line = line.split("//")[0] line = line.strip() if not line: continue # Check if the line is a label (or label plus instruction) # A label is a lowercase word ending in colon. # We allow labels to appear on their own or before an instruction. tokens = line.split() while tokens and tokens[0].endswith(":"): lab = tokens[0][:-1] # remove colon labels[lab] = len(instructions) tokens = tokens[1:] if tokens: instructions.append(tokens) # Helper: function to resolve an argument token to integer value. # It can be either a register like 'R1' or a number (constant). def get_value(token): if token.startswith("R"): return registers[token] else: return int(token) # Now run the program. while ip < len(instructions): inst = instructions[ip] op = inst[0] # For debugging, you could print(ip, inst) if op == "HCF": break elif op == "SET": # SET Rx C: load constant C into register Rx. # (We assume that the constant is provided even if it might be interpreted as register name) reg = inst[1] # Assuming second argument is always a constant. # But if it is a register, we could allow that too: try: registers[reg] = int(inst[2]) except ValueError: # treat it as register value if not an int literal registers[reg] = registers[inst[2]] ip += 1 elif op in ("ADD", "SUB", "MUL", "DIV", "MOD"): # These instructions all have the form: op Rx Ry Rz dest, src1, src2 = inst[1], inst[2], inst[3] a = get_value(src1) b = get_value(src2) if op == "ADD": registers[dest] = a + b elif op == "SUB": registers[dest] = a - b elif op == "MUL": registers[dest] = a * b elif op == "DIV": # Assume integer division. (Division by zero would raise an error.) registers[dest] = a // b elif op == "MOD": registers[dest] = a % b ip += 1 elif op in ("EQ", "NEQ", "LT", "LTE", "GT", "GTE"): # All of these take two register operands (or two arguments that evaluate to ints) a = get_value(inst[1]) b = get_value(inst[2]) if op == "EQ": flag = (a == b) elif op == "NEQ": flag = (a != b) elif op == "LT": flag = (a < b) elif op == "LTE": flag = (a <= b) elif op == "GT": flag = (a > b) elif op == "GTE": flag = (a >= b) ip += 1 elif op == "INC": # INC Rx: increment register by one. r = inst[1] registers[r] += 1 ip += 1 elif op == "DEC": r = inst[1] registers[r] -= 1 ip += 1 elif op == "JMP": # JMP L: unconditional jump label = inst[1] if label not in labels: raise ValueError("Label '%s' not found" % label) ip = labels[label] elif op == "JT": # Jump if flag is True label = inst[1] if flag: if label not in labels: raise ValueError("Label '%s' not found" % label) ip = labels[label] else: ip += 1 elif op == "JF": # Jump if flag is False label = inst[1] if not flag: if label not in labels: raise ValueError("Label '%s' not found" % label) ip = labels[label] else: ip += 1 elif op == "LOAD": # LOAD Rx M: load memory at address M into register. reg = inst[1] addr = get_value(inst[2]) # Ensure address is in range: if not (0 <= addr < len(memory)): raise IndexError("Memory address %d out of range" % addr) registers[reg] = memory[addr] ip += 1 elif op == "STORE": # STORE Rx M: store register value into memory at address M. reg = inst[1] addr = get_value(inst[2]) if not (0 <= addr < len(memory)): raise IndexError("Memory address %d out of range" % addr) memory[addr] = registers[reg] ip += 1 else: raise ValueError("Unknown instruction: %s" % op) return memory |
Running the following program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 | from typing import List def evaluate(program: str): # Initialize state registers = {"R" + str(i): 0 for i in range(1, 9)} flag = False memory = [0] * 100 ip = 0 # instruction pointer # First, split the program into lines and remove comments/whitespace. lines = program.splitlines() # We will build two lists: one for instructions (each as a list of tokens), # and a label mapping: label_name -> index into instructions list. instructions = [] labels = {} # mapping from label: name -> instruction index # Preprocessing: for line in lines: # Remove inline comments - assume comments start with // line = line.split("//")[0] line = line.strip() if not line: continue # Check if the line is a label (or label plus instruction) # A label is a lowercase word ending in colon. # We allow labels to appear on their own or before an instruction. tokens = line.split() while tokens and tokens[0].endswith(":"): lab = tokens[0][:-1] # remove colon labels[lab] = len(instructions) tokens = tokens[1:] if tokens: instructions.append(tokens) # Helper: function to resolve an argument token to integer value. # It can be either a register like 'R1' or a number (constant). def get_value(token): if token.startswith("R"): return registers[token] else: return int(token) # Now run the program. while ip < len(instructions): inst = instructions[ip] op = inst[0] # For debugging, you could print(ip, inst) if op == "HCF": break elif op == "SET": # SET Rx C: load constant C into register Rx. # (We assume that the constant is provided even if it might be interpreted as register name) reg = inst[1] # Assuming second argument is always a constant. # But if it is a register, we could allow that too: try: registers[reg] = int(inst[2]) except ValueError: # treat it as register value if not an int literal registers[reg] = registers[inst[2]] ip += 1 elif op in ("ADD", "SUB", "MUL", "DIV", "MOD"): # These instructions all have the form: op Rx Ry Rz dest, src1, src2 = inst[1], inst[2], inst[3] a = get_value(src1) b = get_value(src2) if op == "ADD": registers[dest] = a + b elif op == "SUB": registers[dest] = a - b elif op == "MUL": registers[dest] = a * b elif op == "DIV": # Assume integer division. (Division by zero would raise an error.) registers[dest] = a // b elif op == "MOD": registers[dest] = a % b ip += 1 elif op in ("EQ", "NEQ", "LT", "LTE", "GT", "GTE"): # All of these take two register operands (or two arguments that evaluate to ints) a = get_value(inst[1]) b = get_value(inst[2]) if op == "EQ": flag = (a == b) elif op == "NEQ": flag = (a != b) elif op == "LT": flag = (a < b) elif op == "LTE": flag = (a <= b) elif op == "GT": flag = (a > b) elif op == "GTE": flag = (a >= b) ip += 1 elif op == "INC": # INC Rx: increment register by one. r = inst[1] registers[r] += 1 ip += 1 elif op == "DEC": r = inst[1] registers[r] -= 1 ip += 1 elif op == "JMP": # JMP L: unconditional jump label = inst[1] if label not in labels: raise ValueError("Label '%s' not found" % label) ip = labels[label] elif op == "JT": # Jump if flag is True label = inst[1] if flag: if label not in labels: raise ValueError("Label '%s' not found" % label) ip = labels[label] else: ip += 1 elif op == "JF": # Jump if flag is False label = inst[1] if not flag: if label not in labels: raise ValueError("Label '%s' not found" % label) ip = labels[label] else: ip += 1 elif op == "LOAD": # LOAD Rx M: load memory at address M into register. reg = inst[1] addr = get_value(inst[2]) # Ensure address is in range: if not (0 <= addr < len(memory)): raise IndexError("Memory address %d out of range" % addr) registers[reg] = memory[addr] ip += 1 elif op == "STORE": # STORE Rx M: store register value into memory at address M. reg = inst[1] addr = get_value(inst[2]) if not (0 <= addr < len(memory)): raise IndexError("Memory address %d out of range" % addr) memory[addr] = registers[reg] ip += 1 else: raise ValueError("Unknown instruction: %s" % op) return memory answer = evaluate(""" SET R1 0 SET R2 1 loop: MUL R3 R2 R2 STORE R3 R1 INC R1 INC R2 SET R3 20 EQ R1 R3 JF loop """)[:10] expected = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] assert answer == expected, f'Wrong answer; got {answer} instead of {expected}' answer = evaluate(""" SET R1 2 // Starting number to check for prime start_find_primes: JMP is_prime // Control will return after executing is_prime with R1 as input and R2 containing the result ready_prime: SET R7 1 EQ R2 R7 // Check if R2 is 1 (prime) JF increment // If not prime, skip storing and increment the number // Store prime number in memory and increment count STORE R1 R8 // Store prime number at address pointed by R8 INC R8 // Increment prime count // Check if 100 primes are found SET R7 100 EQ R8 R7 JF increment // If not 100 primes found yet, continue finding JMP end // If 100 primes found, end program increment: INC R1 // Increment number to check for prime JMP start_find_primes // Check next number is_prime: SET R2 1 // Assume number is prime initially SET R3 2 // Start divisor from 2 start_loop: // Label to start the loop // Check if we have exceeded the square root of R1 MUL R4 R3 R3 // R4 = R3 * R3 GT R4 R1 // Set flag if R4 > R1 JT is_prime_end // If not exceeded, continue; else, end loop MOD R6 R1 R3 // R6 = R1 % R3 SET R7 0 EQ R7 R6 // Check if R6 is 0 JT not_prime // If yes, number is not prime INC R3 // Increment divisor JMP start_loop // Repeat loop not_prime: SET R2 0 // Set result to 0 (not prime) is_prime_end: JMP ready_prime end: """)[:10] expected = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] assert answer == expected, f'Wrong answer; got {answer} instead of {expected}' print('All tests passed') |
All tests passed
Testing if the previous output contains the string All tests passed
: True