112 lines
3.4 KiB
Python
112 lines
3.4 KiB
Python
|
|
|
|
|
|
class AbacusCore:
|
|
|
|
def __init__(self):
|
|
self._input_string = input
|
|
self._vars = dict()
|
|
self._funcs = dict()
|
|
|
|
self._vars['alphabet'] = 28
|
|
self._vars['alpha'] = 1
|
|
self._vars['beta'] = 2
|
|
|
|
self._funcs['r2'] = lambda x: round(x, 2)
|
|
self._funcs['r0'] = lambda x: int(x)
|
|
self._funcs['summe'] = self.summe
|
|
|
|
|
|
def summe(self, l):
|
|
s = 0
|
|
for ss in l:
|
|
s = s + ss
|
|
return s
|
|
|
|
|
|
def _calculate(self, input_str):
|
|
try:
|
|
return True, eval(input_str)
|
|
except ZeroDivisionError:
|
|
res = 'Division by Zero'
|
|
except NameError as e:
|
|
res = 'Variable '+ e.name + ' not exists'
|
|
except SyntaxError as e:
|
|
res = 'Syntax Error'
|
|
return False, res
|
|
|
|
def get_vars(self):
|
|
return self._vars
|
|
|
|
def add_var(self, name, value):
|
|
self._vars[name] = value
|
|
|
|
def parse_input(self, input_str):
|
|
'''
|
|
versuche input_str zu parsen in comment vars und andere teile
|
|
:param input_str:
|
|
:return:
|
|
'''
|
|
input_str, comment = self._get_input_wo_commentar(input_str)
|
|
input_str = ''.join(input_str.split()) # entferne alle leerzeichen
|
|
if input_str is not None:
|
|
for chunk in self._is_new_variable(input_str): # chunks für variablenzuweisung
|
|
self._replace_vars(chunk)
|
|
else:
|
|
return ('comment', comment)
|
|
|
|
|
|
def _replace_vars(self, input_str):
|
|
'''
|
|
try to find vars and replace them
|
|
:param input_str:
|
|
:return:
|
|
'''
|
|
first_position = None
|
|
new_input_str = ''
|
|
for i, c in enumerate(input_str):
|
|
if c.isalpha():
|
|
if first_position is None:
|
|
first_position = i
|
|
# print('alpha'+c)
|
|
elif c == '=':
|
|
if first_position is not None: # variablenzuweisung
|
|
self._vars[input_str[first_position:i]] = None # todo: wie machen?
|
|
else: # keine variable angegeben todo: womöglich eine tempvariable?
|
|
raise ValueError()
|
|
elif c.isnumeric() or c in ['+', '-', '/', '*', '(', ')', '[', ']', ';']:
|
|
if first_position is not None:
|
|
temp_var = input_str[first_position:i]
|
|
print('var', temp_var)
|
|
var = self._vars.get(temp_var)
|
|
if var is not None:
|
|
new_input_str +=str(var)
|
|
else:
|
|
raise ValueError()
|
|
first_position = None
|
|
new_input_str += input_str[i]
|
|
print(new_input_str)
|
|
|
|
def _get_input_wo_commentar(self, input_str):
|
|
'''
|
|
Zerlege input in input und kommentar
|
|
:param input_str:
|
|
:return:
|
|
'''
|
|
input_str = input_str.strip()
|
|
comment_index = input_str.find('#')
|
|
if comment_index == 0: # die ganze zeile ist ein kommentar
|
|
return (None, input_str)
|
|
elif comment_index == -1:
|
|
return (input_str, None)
|
|
else:
|
|
comment = input_str[comment_index + 1:]
|
|
input_str = input_str[:comment_index]
|
|
return (input_str, comment)
|
|
|
|
|
|
def _is_new_variable(self, input_str):
|
|
chunks = input_str.split('=')
|
|
chunks.reverse()
|
|
return chunks
|