Skip to content

Instantly share code, notes, and snippets.

@lwiecek
Last active December 14, 2021 11:57
Show Gist options
  • Save lwiecek/952b6bca77c843e83c5d5577da9fd37e to your computer and use it in GitHub Desktop.
Save lwiecek/952b6bca77c843e83c5d5577da9fd37e to your computer and use it in GitHub Desktop.
Reverse Polish Notation Calculator in Golang
package main
import (
"fmt"
"strconv"
"strings"
)
func pop2(stack []float64) ([]float64, float64, float64) {
var ab []float64
stack, ab = stack[:len(stack)-2], stack[len(stack)-2:]
return stack, ab[0], ab[1]
}
func ReversePolishNotation(s string) (float64, error) {
var stack []float64
var tokens = strings.Fields(s)
var value float64
for _, token := range tokens {
switch token {
case "+", "-", "*", "/":
var a, b float64
if len(stack) < 2 {
return 0, fmt.Errorf("not enough elmenents on the stack to calculate %s", token)
}
stack, a, b = pop2(stack)
switch token {
case "+":
value = a + b
case "-":
value = a - b
case "*":
value = a * b
case "/":
value = a / b
}
default:
var err error
value, err = strconv.ParseFloat(token, 64)
if err != nil {
return 0, fmt.Errorf("invalid token %s", token)
}
}
stack = append(stack, value)
}
if len(stack) != 1 {
return 0, fmt.Errorf("incomplete expression %s", stack)
}
return stack[0], nil
}
func main() {
fmt.Println(ReversePolishNotation("0"))
fmt.Println(ReversePolishNotation("1 2 +"))
fmt.Println(ReversePolishNotation("2 2 + 2 *"))
fmt.Println(ReversePolishNotation("1 100 /"))
fmt.Println(ReversePolishNotation(" 100 1 / "))
fmt.Println(ReversePolishNotation(""))
fmt.Println(ReversePolishNotation("1 2 3"))
fmt.Println(ReversePolishNotation("+ -"))
fmt.Println(ReversePolishNotation("abc"))
fmt.Println(ReversePolishNotation("-1"))
fmt.Println(ReversePolishNotation("-1 -0.0 +"))
fmt.Println(ReversePolishNotation("-2.5 -1e10 *"))
fmt.Println(ReversePolishNotation("0 0 /"))
fmt.Println(ReversePolishNotation("1 0 /"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment