Created
September 8, 2022 01:20
-
-
Save efrenfuentes/d90986c586b8e6a9ba6664a86117204c to your computer and use it in GitHub Desktop.
Python simple calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def add(x, y): | |
return x + y | |
def sub(x, y): | |
return x - y | |
def mul(x, y): | |
return x * y | |
def div(x, y): | |
return x / y | |
ops = {'+': add, '-': sub, '*': mul, '/': div} | |
def tokens_to_numbers(tokens): | |
for i in range(len(tokens)): | |
if is_number(tokens[i]): | |
tokens[i] = float(tokens[i]) | |
return tokens | |
def parse(operation): | |
operation = operation.replace(' ', '') | |
tokens = [] | |
for i in range(len(operation)): | |
if operation[i].isdigit() and i > 0 and (tokens[-1].isdigit() | |
or tokens[-1][-1] == '.'): | |
tokens[-1] += operation[i] | |
elif operation[i] == '.' and i > 0: | |
tokens[-1] += operation[i] | |
else: | |
tokens.append(operation[i]) | |
tokens = tokens_to_numbers(tokens) | |
return tokens | |
def find_index(tokens, operator): | |
if operator in tokens: | |
return tokens.index(operator) | |
else: | |
return 0 | |
def lower(x, y): | |
if x == 0: | |
return y | |
if y == 0: | |
return x | |
if x > y: | |
return y | |
else: | |
return x | |
def find_next(tokens): | |
precedence = lower(find_index(tokens, '*'), find_index(tokens, '/')) | |
if precedence == 0: | |
precedence = lower(find_index(tokens, '+'), find_index(tokens, '-')) | |
return precedence | |
def calculate(tokens): | |
next_operation = find_next(tokens) | |
while(len(tokens) > 1): | |
next_operation = find_next(tokens) | |
result = ops[tokens[next_operation]](tokens[next_operation - 1], tokens[next_operation + 1]) | |
tokens[next_operation] = result | |
tokens.pop(next_operation + 1) | |
tokens.pop(next_operation - 1) | |
return tokens[0] | |
def is_number(value): | |
try: | |
float(value) | |
return True | |
except: | |
return False | |
def calculator(operation): | |
tokens = parse(operation) | |
return calculate(tokens) | |
def main(): | |
operation = input('Enter the operation to solve: ') | |
print(calculator(operation)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment