import sys import operator from time import sleep from math import flo

  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
import sys
import operator
from time import sleep
#from math import floor, abs
class Processor:
def __init__(self):
self.bits = 32
self.stack = []
self.math = {'add': operator.add,
'sub': operator.add,
'mul': operator.mul,
'div': operator.truediv,
'lsh': operator.lshift,
'rsh': operator.rshift,
'xor': operator.xor,
'xor': operator.xor,
'mod': operator.mod,
'and': operator.and_,
'or': operator.or_
}
self.sleep = 1
self.filemode = False
def _split(self, val):
sgn = 0 if val>=0 else 1
val = abs(val)
e = 0
if type(val) != int and type(val) != long:
while ( str(val).split('.')[1]!='0' ) and val<1000000 and e<62:
val *= 10
e -= 1
while (val%10==0 and val>0):
val /= 10
e += 1
sgne = 0 if e>=0 else 1
e = abs(e) & ((1 << 6)-1)
val = int(round(val)) & ((1 << 24)-1)
return (sgn, int(round(val)), sgne, e )
def put(self, val):
#print self._split(val)
self.stack.append(self._split(val))
def pop(self):
res = self.stack.pop()
return ((-1)**res[0])*res[1]*10**((-1)**res[2]*res[3])
def _to_bin(self, stack):
res = str(stack[0])+' '
mant = bin(stack[1])[2:]
while len(mant) < 24:
mant = '0'+mant
res += mant+' '+str(stack[2])+' '
e = bin(stack[3])[2:]
while len(e) < 6:
e = '0'+e
res += e
return res
def print_stack(self):
count=0
for stack in self.stack[::-1]:
print 'Stack['+str(count)+']: '+str(self._to_bin(stack))
count += 1
while count<8:
print 'Stack[%d]: 0 000000000000000000000000 0 000000' % count
count += 1
def process(self, commands):
for command in commands:
if command[0] == 'put':
if command[1].isdigit():
self.put(int(command[1]))
else:
self.put(float(command[1]))
elif command[0] == 'get':
print 'Returned value: %g' % self.pop()
elif command[0] == 'copy':
val = self.pop()
self.put(val)
self.put(val)
elif command[0] == 'rev':
v1 = self.pop()
v2 = self.pop()
self.put(v1)
self.put(v2)
elif command[0] in self.math.keys():
op1 = self.pop()
op2 = self.pop()
self.put(self.math[command[0]](op1,op2))
elif command[0] == 'status':
pass
else:
print ('Wrong command')
continue
self.print_stack()
sleep(self.sleep)
if self.filemode:
raw_input()
#print self.pop()
def main():
p = Processor()
if len(sys.argv)==2:
a = [ c.split() for c in open(sys.argv[1]).read().split('\n') ]
p.sleep=0
p.filemode=True
p.process(a)
else:
p.sleep=0
p.filemode=False
while True:
print "INPUT> ",
a = raw_input()
a = [ a.split() for a in a.split(';') ]
p.process(a)
if __name__ == "__main__":
main()