import sys import operator class Processor def __init__ self if len sy

 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
import sys
import operator
class Processor:
def __init__(self):
if len(sys.argv) < 3:
print "Please specify registers size and addresation type."
raise "Commandline arguments error"
self.bits = int(sys.argv[1])
self.addr = int(sys.argv[2])
self.registers = [0]*4
self.ram = 0
self.math = {'add': operator.add,
'sub': operator.add,
'mul': operator.mul,
'div': operator.div,
'lsh': operator.lshift,
'rsh': operator.rshift,
'xor': operator.xor,
'xor': operator.xor,
'mod': operator.mod,
'and': operator.and_,
'or': operator.or_
}
#def _to_bin(self, number):
def print_registers(self):
"Print current registers content to console"
for number,register in enumerate(self.registers):
string = bin(register)[2:]
while len(string) < self.bits:
string = '0'+string
print "Register %d: %s" % (number+1,string)
def write_register(self, reg, val):
size = ((1 << self.bits)-1)
self.registers[reg-1] = size & val
def process_3adr(self,commands):
"Process commands in 3 addresses"
for command in commands:
print "processing: %s" % ' '.join(command)
if command[0] == 'put':
self.write_register(int(command[1][1]), int(command[2]))
print bin(self.registers[int(command[1][1])-1])[2:]
if command[0] == 'save':
self.ram = self.registers[int(command[2][1])-1]
if command[0] in self.math.keys():
#if command[0] == 'add':
if len(command[2]) == 2 and command[2][0] == 'R':
op1 = self.registers[int(command[2][1])-1]
else:
op1 = int(command[2])
if len(command[3]) == 2 and command[3][0] == 'R':
op2 = self.registers[int(command[3][1])-1]
else:
op2 = int(command[3])
print op1,op2,self.math[command[0]](op1,op2)
self.write_register(int(command[1][1]),
self.math[command[0]](op1,op2))
self.print_registers()
if __name__ == "__main__":
#try:
p = Processor()
while True:
print "INPUT> ",
a = raw_input()
z = a.split()
print z
p.process_3adr([z])
#except:
# print "Exiting."