Files
python/exercises/forth/example.py

59 lines
1.7 KiB
Python
Raw Normal View History

class UnderflowError(Exception):
pass
2017-10-06 16:43:57 -05:00
def is_integer(string):
try:
int(string)
return True
except ValueError:
2017-10-06 16:43:57 -05:00
return False
def evaluate(input_data):
2017-10-06 16:43:57 -05:00
defines = {}
while input_data[0][0] == ':':
values = input_data.pop(0).split()
values.pop()
values.pop(0)
key = values.pop(0)
2017-10-06 16:43:57 -05:00
if is_integer(key):
raise ValueError()
2017-10-06 16:43:57 -05:00
defines[key] = values
stack = []
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:
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 == '/':
divider = stack.pop()
if divider == 0:
raise ZeroDivisionError()
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:
raise ValueError()
except ZeroDivisionError:
raise
except IndexError:
raise UnderflowError()
2017-10-06 16:43:57 -05:00
return stack