Did some cleanup using types. No more string->float->string conversions. Adding old solution below!
from strutils import split, parseFloat from sequtils import foldl proc calculate(input: string): float = var stack: seq[string] = input.split(" ") var backStack: seq[string] while len(stack) > 0: let item = stack.pop() if item == "*": let curr = parseFloat(backStack.pop()) let other = parseFloat(stack.pop()) backStack.add($(other * curr)) elif item == "/": let curr = parseFloat(backStack.pop()) let other = parseFloat(stack.pop()) backStack.add($(other / curr)) else: backStack.add(item) while len(backStack) > 2: let item = parseFloat(backStack.pop()) let operator = backStack.pop() let other = parseFloat(backStack.pop()) if operator == "+": backStack.add($(item + other)) else: backStack.add($(item - other)) return foldl(backStack, a + parseFloat(b), 0.0) when isMainModule: echo $calculate("2 / 2 + 3 * 4 - 6") #7
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Did some cleanup using types. No more string->float->string conversions. Adding old solution below!