Skip to content

Instantly share code, notes, and snippets.

@espio999
Created September 12, 2021 00:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save espio999/f922a7b62a508a7417f35309bf221a9a to your computer and use it in GitHub Desktop.
Save espio999/f922a7b62a508a7417f35309bf221a9a to your computer and use it in GitHub Desktop.
42 SILICON VALLEY Piscine 2017 - evalexpr
def is_number(val):
if val >= '0' and val <= '9':
return True
else:
return False
def my_atoi(val):
global p
local_p = 0
ret = 0
while is_number(val[local_p]) == True:
ret = ret * 10 + int(val[local_p])
local_p += 1
p += 1
return ret
def reformat(val, ary):
global p
minus_flg = 0
while True:
if val[p] == '\n':
ary.append(val[p])
break
if val[p] == ' ':
p += 1
if val[p] == '-':
if is_number(val[p + 1]) == True:
minus_flg = 1
ary.append('(')
ary.append(0)
ary.append('-')
p += 1
continue
if is_number(val[p]) == False:
ary.append(val[p])
p += 1
continue
else:
ary.append(my_atoi(val[p:]))
if minus_flg == 1:
ary.append(')')
minus_flg = 0
def factor(ary):
global i
print('factor', '\t', ary[i:])
if ary[i] == '(':
i += 1
ret = expression(ary)
i += 1
else:
ret = ary[i]
i += 1
return ret
def term(ary):
global i
print('term', '\t', ary[i:])
ret = factor(ary)
while ary[i] != '\n':
if ary[i] == '*':
i += 1
ret = ret * factor(ary)
elif ary[i] == '/':
i += 1
ret = int(ret / factor(ary))
elif ary[i] == '%':
i += 1
ret = int(ret % factor(ary))
else:
break
return ret
def expression(ary):
global i
print('expr', '\t', ary[i:])
ret = term(ary)
while ary[i] != '\n':
if ary[i] == '+':
i += 1
ret = ret + term(ary)
elif ary[i] == '-':
i += 1
ret = ret - term(ary)
else:
break;
return ret
def eval_expr(val):
global p
global i
val = '(' + val + ')' + '\n'
ary = []
p = 0
reformat(val, ary)
i = 0
return expression(ary)
arg = '42'
print('from eval', '\t', eval_expr(arg))
print('from console', '\t', 42)
arg = '-42'
print('from eval', '\t', eval_expr(arg))
print('from console', '\t', -42)
arg = '(-42)'
print('from eval', '\t', eval_expr(arg))
print('from console', '\t', (-42))
arg = '(1+2+3) * (-1) * 10 + 102'
print('from eval', '\t', eval_expr(arg))
print('from console', '\t', (1+2+3) * (-1) * 10 + 102)
arg = '(1+2+3) * -1 * 10 + 102'
print('from eval', '\t', eval_expr(arg))
print('from console', '\t', (1+2+3) * -1 * 10 + 102)
arg = '(-100 - -100 - -100 - -100 * 3) /10 + 2'
print('from eval', '\t', eval_expr(arg))
print('from console', '\t', (-100 - -100 - -100 - -100 * 3) /10 + 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment