Skip to content

Instantly share code, notes, and snippets.

@Ksengine
Last active August 31, 2025 17:12
Show Gist options
  • Select an option

  • Save Ksengine/dc14cc8859db2b27cd55700adc74e2d8 to your computer and use it in GitHub Desktop.

Select an option

Save Ksengine/dc14cc8859db2b27cd55700adc74e2d8 to your computer and use it in GitHub Desktop.
# Kalculator
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
import readline # for better console text edit experience
def isnumeric(number):
for num in range(10):
if str(number[-1])==str(num):
return True
return False
try:
input=raw_input
except:
pass
def kalculator(string):
'''
this is the main function
'''
string = string.replace(' ', '') # remove spaces. spaces will raise exceptions.
string = string.replace('of', '/') # O - of
string = string.replace('**', '^') # O - order by
for num in range(10):
string = string.replace(str(num) + '(', str(num) + '*(')
string = string.replace(')' + str(num), ')*' + str(num))
tokens = []
for char in string: # tokenize calculation
if isnumeric(char):
if len(tokens) > 0 and tokens[-1][-1]=='.':
tokens[-1] += char
elif len(tokens) > 0 and tokens[-1]=='-':
tokens[-1] += char
elif len(tokens) > 0 and isnumeric(tokens[-1]):
tokens[-1] += char
else:
tokens.append(char)
else:
if char=='.':
tokens[-1] += char
else:
tokens.append(char)
while find(tokens, '('): # find brackets B - brackets
start = None
end = None
middle = []
i = 0
for token in tokens: # calculate brackets
if token == '(':
start = i
middle = []
elif token == ')' and end == None:
end = i
tokens = tokens[:start] + calculator(middle) \
+ tokens[end + 1:]
break
else:
middle.append(token)
i += 1
result = calculator(tokens)[0] # last calculation
if result.endswith('.0'):
result=result[:-2]
return result
def calculator(tokens):
'''
calculate brackets less calculations
'''
while find(tokens, '^'): # O - order by
i = 0
for token in tokens:
if token == '^':
tokens[i] = str(float(tokens[i - 1]) ** float(tokens[i
+ 1]))
tokens = tokens[:i - 1] + [tokens[i]] + tokens[i + 2:]
break
i += 1
while find(tokens, '*') or find(tokens, '/'):
i = 0
for token in tokens:
if token == '*': # M - multiplication
tokens[i] = str(float(tokens[i - 1]) * float(tokens[i
+ 1]))
tokens = tokens[:i - 1] + [tokens[i]] + tokens[i + 2:]
break
elif token == '/':
# D - Division
tokens[i] = str(float(tokens[i - 1]) / float(tokens[i
+ 1]))
tokens = tokens[:i - 1] + [tokens[i]] + tokens[i + 2:]
break
i += 1
while find(tokens, '+') or find(tokens, '-'):
i = 0
for token in tokens:
if token == '+': # A - Addition
tokens[i] = str(float(tokens[i - 1]) + float(tokens[i
+ 1]))
tokens = tokens[:i - 1] + [tokens[i]] + tokens[i + 2:]
break
elif token == '-':
# S - Subtraction
tokens[i] = str(float(tokens[i - 1]) - float(tokens[i
+ 1]))
tokens = tokens[:i - 1] + [tokens[i]] + tokens[i + 2:]
break
i += 1
return tokens
def find(l, m):
# list find function
for item in l:
if item == m:
return True
return False
if __name__ == '__main__':
while True:
i = input('>')
try:
print(kalculator(str(i)))
except Exception as e:
print('Error : ',str(e).replace('float','number'))
@Ksengine
Copy link
Author

Ksengine commented Jul 3, 2020

Kalculator

Use BODMAS method

  1. B - brackets ()
  2. O - of / order by ** ^
  3. D - division /
  4. M - multiplication *
  5. A - addition +
  6. S - subtraction -

this is a good example for developers.
i thinked hard.
at last I developed my own methods.
you can use python built-in calculator eg-:eval(input('>'))
but i made my own method.
this is a foundation for a interpreter.
thinking is the important thing.

Bye!

@Ksengine
Copy link
Author

minus and point supported

@johnzhou721
Copy link

Nice! I had to do this for a coding competition once, and my method was basically to find the highest order operation in the string, split it into half and then run it over the two halves until you get (x) or x

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment