pc = 0
registers[code[pc]['register1']]
labels[code[pc]['labeldef']]
class Rational:
def __init__(self,n,d):
self.numerator = n
self.denominator = d
self.reduce()
def add(self,r):
num = self.numerator * r.denominator + self.deniminator * r.numerator
den = self.denominator * r.denominator
return Rational(num,den)
# please write mul, div, minus methods
@staticmethod
def gcd(m,n): # assume m >= n
while n != 0:
r = m%n
m = n
n = r
return m
def reduce(self):
#if self.numerator > self.denominator:
# g = gcd(self.numerator,self.denominator)
#else:
# g = gcd(self.denominator,self.numerator)
g = Rational.gcd(self.numerator,self.denominator)
if g == 0:
return None
elif self.numerator < 0 and self.denominator < 0:
self.numerator = -self.numerator / g
self.denominator = -self.denominator / g
elif ... + num, - den
elif ... -num, + den
else: +num, +den
def __str__(self): # should return string version of the object
return str(self.numerator) + " / " + str(self.denominator)
r1 = Rational(18,12)
r2 = Rational(15,6)
r3 = r1.add(r2)
...
...
print(r3)
code = [ {'labeldef': 'N0', 'opcode': 'CJMP', 'register1': 'R2', 'jmplabel': 'N1'},
{'opcode': 'INC', 'register1': 'R1'},
{'opcode': 'DEC', 'register1': 'R2'},
{'opcode': 'UJMP', 'jmplabel': 'N0'},
{'labeldef': 'N1', 'opcode': 'CONTINUE'}
]
def construct_labels_from_code(code):
labels = {}
for ino,ins in enumerate(code):
if "labeldef" in ins:
labels[ins["labeldef"]] = ino
return labels
construct_labels_from_code(code)
{'N0': 0, 'N1': 4}