82 lines
2.5 KiB
Python
82 lines
2.5 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)
|
|
|
|
def _calculate(self, input):
|
|
return eval(input)
|
|
|
|
def parse_input(self, input):
|
|
comment = None
|
|
input_wo_com = None
|
|
input = str(input).strip()
|
|
input = input.replace(',', '.')
|
|
if input[0] == '#':
|
|
comment = input[1:]
|
|
com_index = input.find('#')
|
|
if com_index > -1:
|
|
input_wo_com = input[:com_index]
|
|
comment = input[com_index+1:]
|
|
if input_wo_com is None:
|
|
input_wo_com = input
|
|
print('comment', comment)
|
|
result = self._split_input(input_wo_com)
|
|
print('result:',result)
|
|
if result[1] is not None:
|
|
res = self._calculate(result[1])
|
|
print(res)
|
|
operators = result[0]
|
|
operators.reverse()
|
|
for op in operators:
|
|
if op[-1] == '=':
|
|
self._vars[op[:-1]] = res
|
|
elif op[-1] == ':':
|
|
res = self._funcs.get(op[:-1])(res)
|
|
print('vars:', self._vars)
|
|
|
|
|
|
def _split_input(self, input):
|
|
last_position = 0
|
|
varchunks = list()
|
|
for i, c in enumerate(input):
|
|
if c in [':', '=']:
|
|
chunk = input[last_position:i].strip()
|
|
chunk = chunk+input[i]
|
|
varchunks.append(chunk)
|
|
last_position = i+1
|
|
rest = input[last_position:].strip()
|
|
print('rest', rest)
|
|
rest = self._find_vars(rest)[1]
|
|
return (varchunks, rest)
|
|
|
|
def _find_vars(self, input):
|
|
chunks = list()
|
|
last_position = 0
|
|
for i, c in enumerate(input):
|
|
if c in ['+', '-', '/', '*', '(', ')', '[', ']', ';']:
|
|
ch = input[last_position:i].strip()
|
|
if len(ch)>0:
|
|
chunks.append(ch)
|
|
chunks.append(input[i].strip())
|
|
last_position = i+1
|
|
|
|
if last_position<len(input):
|
|
chunks.append(input[last_position:].strip())
|
|
cp_chunks = chunks.copy()
|
|
for i, chunk in enumerate(chunks):
|
|
if chunk in self._vars:
|
|
cp_chunks[i] = str(self._vars.get(chunk))
|
|
print(chunks, cp_chunks)
|
|
return (len(cp_chunks)>1, ''.join(cp_chunks)) |