Files
python/exercises/practice/forth/.meta/example.py

63 lines
1.9 KiB
Python
Raw Normal View History

class StackUnderflowError(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):
if not input_data:
return []
2017-10-06 16:43:57 -05:00
defines = {}
while input_data[0][:1] == ':':
values = input_data.pop(0).split()
values.pop()
values.pop(0)
key = values.pop(0).lower()
2017-10-06 16:43:57 -05:00
if is_integer(key):
raise ValueError("Integers cannot be redefined")
2018-07-20 14:33:17 -04:00
defines[key] = [
x
for v in values
for x in defines.get(v, [v])
]
2017-10-06 16:43:57 -05:00
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 == '/':
divisor = stack.pop()
if divisor == 0:
raise ZeroDivisionError("Attempted to divide by zero")
stack.append(int(stack.pop() / divisor))
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("{} has not been defined".format(word))
except IndexError:
raise StackUnderflowError("Insufficient number of items in stack")
2017-10-06 16:43:57 -05:00
return stack