Microsoft MVP성태의 닷넷 이야기
.NET Framework: 530. C# - 중위식을 후위식으로 변환하는 예제 [링크 복사], [링크+제목 복사],
조회: 16940
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

C# - 중위식을 후위식으로 변환하는 예제

이번엔 별다르게 쓸 이야기는 없고, 단순히 다음의 글에 실린 파이썬 코드를 C#에 대응시켜 변환해 봤습니다.

후위식 변환
; http://soooprmx.com/wp/archives/5127

첨부 파일에도 넣어두었지만, 다음은 해당 코드입니다.

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Expression.ConvertToPostFix("A + B * C"));
            // 출력: A B C * +

            Console.WriteLine(Expression.ConvertToPostFix("( A + B ) * C"));
            // 출력: A B + C *

            Console.WriteLine(Expression.ConvertToPostFix("( A + B ) * ( C + D )"));
            // 출력: A B + C D + *
        }
    }

    class Expression
    {
        public static string ConvertToPostFix(string expStr)
        {
            // 1. 수식을 각 토큰별로 구분하여 읽어들인다
            string[] tokens = expStr.Split(' ');

            string[] ops = new string[] { "+", "-", "*", "/", "(", ")" };
            Dictionary<string, int> precs = new Dictionary<string, int>
            {
                ["*"] = 2,
                ["/"] = 2,
                ["+"] = 1,
                ["-"] = 1,
                ["("] = 0,
            };

            Stack<string> opStack = new Stack<string>(); // 스택
            List<string> output = new List<string>(); // 출력 리스트

            foreach (string item in tokens)
            {
                if (ops.Contains(item) == false)
                {
                    // 2. 토큰이 피 연산자이면 출력 리스트에 넣는다.
                    output.Add(item);
                }
                else if (item == "(")
                {
                    // 3. 토큰이 왼쪽 괄호이면 스택에 푸시한다.
                    opStack.Push(item);
                }
                else if (item == ")")
                {
                    // 5. 토큰이 오른쪽 괄호이면 왼쪽 괄호가 나올 때까지 스택에서 팝하여 순서대로 리스트에 넣는다.
                    while (opStack.Peek() != "(")
                    {
                        output.Add(opStack.Pop());
                    }

                    // 왼쪽 괄호 자체는 버린다.
                    opStack.Pop();
                }
                else
                {
                    // 4. 토큰이 연산자이면, 
                    while (opStack.Count != 0)
                    {
                        if (precs[opStack.Peek()] >= precs[item])
                        {
                            // 스택에 있는 연산자의 우선 순위가 자신보다 높거나 같다면 출력 리스트에 이어 붙여준다.
                            output.Add(opStack.Pop());
                        }
                        else
                        {
                            break;
                        }
                    }

                    opStack.Push(item);
                }
            }

            // 6. 더 이상 읽을 토큰이 없다면, 스택에서 연산자를 팝하여 붙인다.
            while (opStack.Count != 0)
            {
                output.Add(opStack.Pop());
            }

            return string.Join(" ", output);
        }
    }
}

C# 소스코드가 파이썬에 비해 코드량이 많을지언정, Visual Studio의 디버깅 기능을 켜놓고 Step-into/over 및 Watch 창을 이용해 따라가시면 훨씬 빠르게 코드를 이해할 수 있답니다. ^^




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 9/15/2015]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
11904정성태5/21/201916641.NET Framework: 833. C# - Open Hardware Monitor를 이용한 CPU 온도 정보 [1]파일 다운로드1
11903정성태5/21/201911681오류 유형: 540. .NET Core - System.PlatformNotSupportedException: The named version of this synchronization primitive is not supported on this platform.
11902정성태5/21/201910860오류 유형: 539. mstest 실행 시 "The directory name is invalid." 오류 발생
11901정성태5/21/201911994오류 유형: 538. msbuild 오류 - Could not find a part of the path '%LOCALAPPDATA%\Temp\2\.NETFramework,Version=v4.0.AssemblyAttributes.cs'
11900정성태5/18/201911288오류 유형: 537. "sfc /scannow" 실행 중 시스템이 부팅되는 현상
11899정성태5/17/201912268Linux: 9. Linux에서 윈도우의 OutputDebugString 대신 사용할 수 있는 syslog [1]
11898정성태5/16/201913633VC++: 130. C++ string의 c_str과 data 함수의 차이점 [3]
11897정성태5/16/201920226오류 유형: 536. Visual Studio - "Developer Pack"을 설치했는데도 "대상 프레임워크" 목록에 나오지 않는 경우 [2]
11896정성태5/15/201914999개발 환경 구성: 440. C#, C++ - double의 Infinity, NaN 표현 방식파일 다운로드1
11895정성태5/12/201913399.NET Framework: 832. ML.NET Model Builder - 회귀(Regression), 다중 분류(Multi-class classification) 예제파일 다운로드1
11894정성태5/10/201914559VS.NET IDE: 135. Visual Studio - ML.NET Model Builder 소개 [5]
11893정성태5/10/201912273오류 유형: 535. C# 6.0 이상의 문법을 컴파일 시 오류가 발생한다면?
11892정성태5/10/201912340웹: 38. HTTP Cookie의 expires 시간 형식(RFC7231)
11891정성태5/9/201914837.NET Framework: 831. (번역글) .NET Internals Cookbook Part 12 - Memory structure, attributes, handles
11890정성태5/8/201910552개발 환경 구성: 439. "Visual Studio Enterprise is required to execute the test." 메시지와 관련된 코드 기록
11889정성태5/8/201911316개발 환경 구성: 438. mstest, QTAgent의 로그 파일 설정 방법
11888정성태5/8/201926446.NET Framework: 830. C# - 비동기 호출을 취소하는 CancellationToken의 간단한 예제 코드 [1]파일 다운로드1
11887정성태5/8/201913119.NET Framework: 829. C# - yield 문을 사용할 수 있는 메서드의 조건
11886정성태5/7/201912160오류 유형: 534. mstest.exe 실행 시 "Visual Studio Enterprise is required to execute the test." 오류 [2]
11885정성태5/7/20199148오류 유형: 533. mstest.exe 실행 시 "File extension specified '.loadtest' is not a valid test extension." 오류 발생
11884정성태5/5/201912847.NET Framework: 828. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 두 번째 이야기
11883정성태5/3/201917075.NET Framework: 827. C# - 인터넷 시간 서버로부터 받은 시간을 윈도우에 적용하는 방법파일 다운로드1
11882정성태5/2/201914039.NET Framework: 826. (번역글) .NET Internals Cookbook Part 11 - Various C# riddles파일 다운로드1
11881정성태4/28/201914318오류 유형: 532. .NET Core 프로젝트로 마이그레이션 시 "CS0579 Duplicate 'System.Reflection.AssemblyCompanyAttribute' attribute" 오류 발생
11880정성태4/25/201911087오류 유형: 531. 이벤트 로그 오류 - Task Scheduling Error: m->NextScheduledSPRetry 1547, m->NextScheduledEvent 1547
11879정성태4/24/201916342.NET Framework: 825. (번역글) .NET Internals Cookbook Part 10 - Threads, Tasks, asynchronous code and others파일 다운로드2
... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...