Skip to content

Instantly share code, notes, and snippets.

@kupp1
Created July 11, 2018 16:05
Show Gist options
  • Save kupp1/3e0987d8ebbe8557c18a2fad26a54ba5 to your computer and use it in GitHub Desktop.
Save kupp1/3e0987d8ebbe8557c18a2fad26a54ba5 to your computer and use it in GitHub Desktop.
Python3 string calculator
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from calc_parser import calc_parser
def evaluate(expression: list):
for i in range(len(expression)):
if expression[i] != '+' and expression[i] != '-' and expression[i] != '*' and expression[i] != '/':
if '.' in expression[i]:
expression[i] = float(expression[i])
else:
expression[i] = int(expression[i])
while '/' in expression or '*' in expression:
for i, _ in enumerate(expression):
if expression[i] == '/':
expression[i] = expression[i-1] / expression[i+1]
del expression[i+1]
del expression[i-1]
elif expression[i] == '*':
expression[i] = expression[i-1] * expression[i+1]
del expression[i+1]
del expression[i-1]
while '-' in expression:
for i, _ in enumerate(expression):
if expression[i] == '-':
expression[i] = expression[i-1] - expression[i+1]
del expression[i+1]
del expression[i-1]
while '+' in expression:
for i, _ in enumerate(expression):
if expression[i] == '+':
expression[i] = expression[i-1] + expression[i+1]
del expression[i+1]
del expression[i-1]
return expression[0]
# examples:
# «8 * 5.003 / 5.34 + 8 - 3.4» > 12.095131086142322
# «65 * 90 - 56 / 9.0» > 5843.777777777777
# «562/832 * 732+ 32» > 526.4519230769231
# «324*32+87» > 10455
string = input()
expression = calc_parser(string)
print(evaluate(expression))
#!/usr/bin/python3
# -*- coding: utf-8 -*-
def calc_parser(string: str):
digits = [
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'
]
dot = '.'
def _isint(string: str):
for char in string:
if not (char in digits):
return False
return True
def _isfloat(string: str):
for char in string:
if not (char in digits):
if not (char is dot):
return False
if dot in string:
return True
else:
return False
rslt = []
i = 0
while len(string) > 1 and ('+' in string or '-' in string or '/' in string or '*' in string):
if string[i] == '+' or string[i] == '-' or string[i] == '/' or string[i] == '*':
if _isint(string[:i]) or _isfloat(string[:i]):
rslt.append(string[:i])
rslt.append(string[i])
if len(string) > 1:
string = string[i + 1:]
else:
string = ''
else:
return []
i = 0
elif string[i] == ' ':
string = '%s%s' % (string[:i], string[i + 1:])
else:
i += 1
rslt.append(string)
return rslt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment