2017-10-06 16:43:57 -05:00
|
|
|
def is_integer(string):
|
|
|
|
|
try:
|
|
|
|
|
int(string)
|
|
|
|
|
return True
|
|
|
|
|
except:
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
2017-10-09 09:10:33 -05:00
|
|
|
def evaluate(input_data):
|
2017-10-06 16:43:57 -05:00
|
|
|
defines = {}
|
2017-10-09 09:10:33 -05:00
|
|
|
while input_data[0][0] == ':':
|
|
|
|
|
values = input_data.pop(0).split()
|
2017-10-06 16:47:16 -05:00
|
|
|
values.pop()
|
|
|
|
|
values.pop(0)
|
|
|
|
|
key = values.pop(0)
|
2017-10-06 16:43:57 -05:00
|
|
|
if is_integer(key):
|
|
|
|
|
return None
|
|
|
|
|
defines[key] = values
|
|
|
|
|
stack = []
|
2017-10-09 09:10:33 -05:00
|
|
|
input_data = input_data[-1].split()
|
|
|
|
|
while any(input_data):
|
|
|
|
|
word = input_data.pop(0).lower()
|
2017-10-06 16:43:57 -05:00
|
|
|
try:
|
|
|
|
|
if is_integer(word):
|
|
|
|
|
stack.append(int(word))
|
|
|
|
|
elif word in defines:
|
2017-10-09 09:10:33 -05:00
|
|
|
input_data = defines[word] + input_data
|
2017-10-06 16:43:57 -05:00
|
|
|
elif word == '+':
|
|
|
|
|
stack.append(stack.pop() + stack.pop())
|
|
|
|
|
elif word == '-':
|
|
|
|
|
stack.append(-stack.pop() + stack.pop())
|
|
|
|
|
elif word == '*':
|
|
|
|
|
stack.append(stack.pop() * stack.pop())
|
|
|
|
|
elif word == '/':
|
2017-10-06 16:47:16 -05:00
|
|
|
divider = stack.pop()
|
|
|
|
|
stack.append(int(stack.pop() / divider))
|
2017-10-06 16:43:57 -05:00
|
|
|
elif word == 'dup':
|
|
|
|
|
stack.append(stack[-1])
|
|
|
|
|
elif word == 'drop':
|
|
|
|
|
stack.pop()
|
|
|
|
|
elif word == 'swap':
|
|
|
|
|
stack.append(stack[-2])
|
|
|
|
|
del stack[-3]
|
|
|
|
|
elif word == 'over':
|
|
|
|
|
stack.append(stack[-2])
|
|
|
|
|
else:
|
|
|
|
|
return None
|
|
|
|
|
except:
|
|
|
|
|
return None
|
|
|
|
|
return stack
|