ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [백준] Go, Python - 후위 표기식 2
    개발/알고리즘 2021. 9. 17. 22:20

    https://www.acmicpc.net/problem/1935

     

    1935번: 후위 표기식2

    첫째 줄에 피연산자의 개수(1 ≤ N ≤ 26) 가 주어진다. 그리고 둘째 줄에는 후위 표기식이 주어진다. (여기서 피연산자는 A~Z의 영대문자이며, A부터 순서대로 N개의 영대문자만이 사용되며, 길이

    www.acmicpc.net

     

    후위 표기식 문제다. 문제 자체는 정말 쉽다.

    그런데 Go로 한번 해보겠다고 Go로 코드 짰는데 계속 틀렸다고 나온다.

    귀신같이 파이썬으로 알고리즘만 유지해서 작성하니까 맞았다...

     

    열받네...

     

    Go, Python 코드는 아래서 확인

    더보기

    참고로 Go 코드는 틀린 코드라고 나온다! 누군가 무슨 문제인지 안다면 알려주....

    https://github.com/Floodnut/Algorithm/tree/main/baekjoon/1935

    import sys
    
    num = []
    
    class Stack:
        def __init__(self):
            self.items = []
        def push(self, item): 
            self.items.append(item)
        def pop(self):
            return self.items.pop()
    
    def postfix(string, numList):
        stack = Stack()
        tmp1, tmp2 = -1, -1
        for i in string:
            if ord(i) == 43:
                tmp1 = float(stack.pop())
                tmp2 = float(stack.pop())
                stack.push(tmp2 + tmp1)
                #print(tmp2 + tmp1)
            elif ord(i) == 45:
                tmp1 = float(stack.pop())
                tmp2 = float(stack.pop())
                stack.push(tmp2 - tmp1)
                #print(tmp2 - tmp1)
            elif ord(i) == 42:
                tmp1 = float(stack.pop())
                tmp2 = float(stack.pop())
                stack.push(tmp2 * tmp1)
                #print(tmp2 * tmp1)
            elif ord(i) == 47:
                tmp1 = float(stack.pop())
                tmp2 = float(stack.pop())
                stack.push(tmp2 / tmp1)
                #print(tmp2 / tmp1)
            else:
                stack.push(numList[ord(i)-65])
                
        return stack.pop()
    
    numCnt = sys.stdin.readline().strip()
    notation = sys.stdin.readline().strip()
    for cnt in range(int(numCnt)):
        num.append(sys.stdin.readline().strip())
    
    #print(notation)
    print("{:.2f}".format(postfix(notation, num)))

    package main
    
    import (
    	"bufio"
    	"fmt"
    	"math"
    	"os"
    	"strconv"
    )
    
    type Stack struct {
    	items []float32
    }
    
    func (s *Stack) Push(item float32) {
    	s.items = append(s.items, item)
    }
    
    func (s *Stack) Pop() float32 /*, errors*/ {
    	dLen := len(s.items)
    	/*
    		if dLen == 0 {
    			return -1, errors.New("No Data")
    		}*/
    	item, items := s.items[dLen-1], s.items[0:dLen-1]
    	s.items = items
    	return item //, nil
    }
    
    func postfix(notation string, num []int) float32 {
    	s := Stack{}
    	var tmp1, tmp2 float32
    	for i := 0; i < len(notation); i++ {
    		if notation[i] == 43 { //+
    			tmp1 = s.Pop()
    			tmp2 = s.Pop()
    			s.Push(tmp1 + tmp2)
    			//fmt.Printf("[+] ")
    			//fmt.Println(tmp1, tmp2, tmp1+tmp2, notation[i])
    		} else if notation[i] == 45 { //-
    			tmp1 = s.Pop()
    			tmp2 = s.Pop()
    			s.Push(tmp2 - tmp1)
    			//fmt.Printf("[-] ")
    			//fmt.Println(tmp1, tmp2, tmp1+tmp2, notation[i])
    		} else if notation[i] == 42 { //*
    			tmp1 = s.Pop()
    			tmp2 = s.Pop()
    			s.Push(tmp1 * tmp2)
    			//fmt.Printf("[*] ")
    			//fmt.Println(tmp1, tmp2, tmp1*tmp2, notation[i])
    		} else if notation[i] == 47 { // /
    			tmp1 = s.Pop()
    			tmp2 = s.Pop()
    			s.Push(tmp2 / tmp1)
    			//fmt.Printf("[/] ")
    			//fmt.Println(tmp1, tmp2, tmp1/tmp2, notation[i])
    		} else {
    			s.Push(float32(num[notation[i]-65]))
    		}
    	}
    	return s.Pop()
    }
    
    func main() {
    	var n int
    	nums := []int{}
    	var compute string
    	scanner := bufio.NewScanner(os.Stdin)
    	scanner.Split(bufio.ScanWords)
    	fmt.Scan(&n)
    	fmt.Scan(&compute)
    	for i := 0; i < n; i++ {
    		scanner.Scan()
    		k, _ := strconv.Atoi(scanner.Text())
    		nums = append(nums, k)
    	}
    	//fmt.Println(nums)
    	rst := math.Trunc(float64(postfix(compute, nums)*100)) / 100
    	prt := fmt.Sprintf("%.2f", rst)
    
    	fmt.Println(prt)
    }

    '개발 > 알고리즘' 카테고리의 다른 글

    [백준] Python - 최소 스패닝 트리  (0) 2021.10.09
    [백준] Python - 트리 순회  (0) 2021.09.24
    [백준] Python - 최대힙  (0) 2021.09.19
    [백준] Python - 그룹 단어 체커  (0) 2021.09.09
    [백준] Python - 염색체  (0) 2021.09.09

    댓글

Designed by Tistory.