This program demonstrates how to evaluate a postfix expression using a stack in Go. Postfix expressions are advantageous in computational contexts because they remove the need for parentheses to dictate the order of operations, allowing for straightforward machine parsing and evaluation.

Program Code

package main

import (
    "fmt"
    "strconv"
    "strings"
)

// Stack type using a slice for storage
type Stack struct {
    elements []int
}

// Push adds an element to the stack
func (s *Stack) Push(value int) {
    s.elements = append(s.elements, value)
}

// Pop removes the top element from the stack and returns it
func (s *Stack) Pop() int {
    if len(s.elements) == 0 {
        panic("pop from empty stack")
    }
    lastIndex := len(s.elements) - 1
    top := s.elements[lastIndex]
    s.elements = s.elements[:lastIndex]
    return top
}

// EvaluatePostfix evaluates a given postfix expression string
func EvaluatePostfix(expression string) int {
    var s Stack
    tokens := strings.Fields(expression)

    for _, token := range tokens {
        switch token {
        case "+", "-", "*", "/":
            right := s.Pop()
            left := s.Pop()
            switch token {
            case "+":
                s.Push(left + right)
            case "-":
                s.Push(left - right)
            case "*":
                s.Push(left * right)
            case "/":
                s.Push(left / right)
            }
        default:
            value, err := strconv.Atoi(token)
            if err != nil {
                panic("invalid token")
            }
            s.Push(value)
        }
    }
    return s.Pop()
}

func main() {
    expression := "3 4 2 * 1 5 - 2 3 ^ ^ / +"
    fmt.Println("Postfix Expression:", expression)
    result := EvaluatePostfix(expression)
    fmt.Println("Evaluated Result:", result)
}

Explanation

  • Stack Operations: The program defines a simple stack type that supports Push and Pop operations to manage integers, facilitating the evaluation process.
  • Evaluating the Postfix Expression: The function EvaluatePostfix parses and evaluates the expression:
    • Numerical tokens are directly pushed onto the stack.
    • When an operator is encountered, the appropriate number of operands (two for binary operators) are popped from the stack, the operation is performed, and the result is pushed back onto the stack.
  • Result Retrieval: At the end of the expression, the stack should contain only one element, the result of the expression, which is returned by the final Pop.

 

Running the Program

To execute this program:

  1. Save the code in a file named evaluatepostfix.go.
  2. Open a terminal or command prompt.
  3. Navigate to the directory containing your file.
  4. Type go run evaluatepostfix.go to run the program.

The output will display the original postfix expression and its evaluated result, demonstrating how the stack is used to perform the calculation step-by-step.

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)