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)
	}
}

  

最新文章

  1. C#+OpenGL+FreeType显示3D文字(1) - 从TTF文件导出字形贴图
  2. 给 C# 开发者的代码审查清单
  3. Code First :使用Entity. Framework编程(6) ----转发 收藏
  4. Libgdx 循环绘制图片时间隔的问题
  5. Redis Lua脚本原理
  6. mysql5.7.11安装配置
  7. Jenkins快速上手
  8. Libsvm的MATLAB调用和交叉验证
  9. sql语句分组统计出年月日下数据记录数目
  10. poj 3678 Katu Puzzle(Two Sat)
  11. underscorejs-every学习
  12. putty修改编码
  13. ubuntu16 网络设置
  14. 无法加载shockwave flash
  15. python中html解析-Beautiful Soup
  16. python读文件指定行的数据
  17. LINQ的增删改查写法&&组合查询
  18. 第九次Scrum meeting
  19. 【TensorFlow】CNN
  20. EditPLus添加到右键图文教程

热门文章

  1. Java生鲜电商平台-生鲜电商中商品类目、属性、品牌、单位架构设计与实战
  2. Flask 教程 第十一章:美化
  3. [springMvc]常见配置
  4. [Go]TCP服务中增加消息队列与工作池
  5. 【转载】解决:'webpack-dev-server' 不是内部或外部命令,也不是可运行的程序 或批处理文件。
  6. uiautomatorviewer 报错 Error while obtaining UI hierarchy XML file: com.android.ddmlib.SyncException: Remote object doesn't exist!
  7. pytest系列(一):什么是单元测试界的高富帅?
  8. import com.sun.org.apache.xml.internal.security.utils.Base64问题
  9. 微信小程序的坑(持续更新中)
  10. 03-MySQL安装与配置