标签:mamicode erro ota false case ret length tac temp
interpreter.go
package interpreter
import (
//"fmt"
"strconv"
"strings"
)
const (
SUM = "sum"
SUB = "sub"
MUL = "mul"
DIV = "div"
)
type polishNotationStack []int
func (p *polishNotationStack) Push(s int) {
*p = append(*p, s)
}
func (p *polishNotationStack) Pop() int {
length := len(*p)
if length > 0 {
temp := (*p)[length-1]
*p = (*p)[:length-1]
return temp
}
return 0
}
func Calculate(o string) (int, error) {
stack := polishNotationStack{}
operators := strings.Split(o, " ")
for _, operatorString := range operators {
if isOperator(operatorString) {
right := stack.Pop()
left := stack.Pop()
mathFunc := getOperationFunc(operatorString)
res := mathFunc(left, right)
stack.Push(res)
} else {
val, err := strconv.Atoi(operatorString)
if err != nil {
return 0, err
}
stack.Push(val)
}
}
return int(stack.Pop()), nil
}
func isOperator(o string) bool {
if o == SUM || o == SUB || o == MUL || o == DIV {
return true
}
return false
}
func getOperationFunc(o string) func(a, b int) int {
switch o {
case SUM:
return func(a, b int) int {
return a + b
}
case SUB:
return func(a, b int) int {
return a - b
}
case MUL:
return func(a, b int) int {
return a * b
}
case DIV:
return func(a, b int) int {
return a / b
}
}
return nil
}
interpreter_test.go
package interpreter
import (
"testing"
)
func TestCalculate(t *testing.T) {
tempOperation := "3 4 sum 2 sub"
res, err := Calculate(tempOperation)
if err != nil {
t.Error(err)
}
if res != 5 {
t.Errorf("Expected result not found: %d != %d\n", 5, res)
}
tempOperation = "5 3 sub 8 mul 4 sum 5 div"
res, err = Calculate(tempOperation)
if err != nil {
t.Error(err)
}
if res != 4 {
t.Errorf("Expected result not found: %d != %d\n", 4, res)
}
}

标签:mamicode erro ota false case ret length tac temp
原文地址:https://www.cnblogs.com/aguncn/p/11916892.html