들어가기
의사코드를 자주 사용하거나 활용하는 빈도는 많지가 않다. 의사코드는 알고 있지만 사용하려면 어떻게 시작할지 모른다. 대부분 개발할 때 상세 설계없이 바로 구현하는 경우가 대부분이기에 활용할 기회가 거의 없다. 그러나 알게모르게 구현하는 과정에서 활용되고 있다. 가끔 코드에 작성된 주석이 이에 해당한다고 볼 수 있다. 의사코드가 무엇인지 느낌을 잡아보자.
작성자: ospace114@empal.com, http://ospace.tistory.com/
의사코드란?
의사코드란 컴퓨터 프로그래밍 전에 사람의 언어로 프로그래밍 언어 형식을 빌어서 간단하게 표현하는 코드이다.
의사코드를 사용하는 이유는
- 자신의 생각을 명확하게 만들거나, 로직 설계를 사전에 검증
- 리뷰를 쉽게 진행하는데 도움
- 반복을 통한 정재 진행
- 변경이 쉬워짐
- 주석에 대한 노력이 최소화
- 설계문서 유지보수 노력이 쉬워짐
표현하는 형태의 일반적인 언어적 표현을 사용할 수 있고 구조화된 언어적 표현을 사용할 수도 있다. 이 부분은 정해진 부분은 없고 각자 정해서 사용한다. 일반적 언어 표현은 이해가기는 쉽지만, 쉽게 코드로 작업하기 힘들다. 구조화된 언어적 표현은 익숙해지는데 어려움이 있지만 쉽게 코드로 작성할 수 있다.
일반적 언어 표현
예제1-세금계산
세금을 고려한 아이템 최종 가격을 계산하는 의사코드
- get price of item
- get sales tax rate
- sales tax = price of item times sales tax rate
- final price = price of item plus sales tax
- display final price
- halt
Variables: price of item, sales tax rate, sales tax, final price
각 연산은 번호을 붙여졌고 각 연산은 명확하고 효율적으로 계산되도록 한다. 의사코드에서 사용되는 모든 변수를 추출할 수 있다. 이는 프로그래밍 언어로 작성할 때 유용하다. 이 의사코드를 실제 코드로 작성하면
def compute_salestax():
# get price of item
price = float(raw_input("What is the item's price? ")
# get sales tax rate
tax_rate = float(raw_input("Enter the sales tax rate, in decimal: ")
# sales tax = price of item times sales tax rate tax = price * tax_rate
# final price = price of item plus sales tax final_price = price + tax
# display final price
print "The final price is:", final_price
# halt
return
코드에 주석으로 의사코드가 포함되어 있다.
예제2: 퀴즈 평균 계산
다음은 퀴즈 점수의 평균을 계산하는 의사코드이다.
Get number of quizzes as a parameter
- Initialize "sum" and "count" variables to 0
- while count < number of quizzes
2.1. get quiz grade
2.2. add quiz grade to "sum"
2.3. increment count - compute average of sum over number of quizzes
- return average
이대로 충분해 보이지만 좋아보이지만 다르게 접근해보자.
Get a list of quiz grades as a parameter
- Initialize "sum" variable to 0
- Go through each quiz grade in the list
2.1 add quiz grade to "sum" - compute average of sum over number of quizzes
- return average
두개 버전의 의사코드이다. 둘 중에 하나를 선택해서 구현할 수 있다.
두 번째 버전은 더 짧고 사용자 입력에 의존하지 않는다. 코딩 측변에서 두 번째 버전이 더 좋아보인다. 이 버전을 구현해보자.
# Get a list of quiz grades as a parameter
def compute_quiz_average(quiz_grade_list):
# Initialize "sum" variable to 0
sum = 0
# Go through each quiz grade in the list
for qgrade in quiz_grade_list:
# add quiz grade to "sum"
sum += qgrade
# compute average of sum over number of quizzes num_quizzes = len(quiz_grade_list)
average = float(sum)/num_quizzes
# return average
return average
구조화된 언어 표현
의사코드 표기법에 일반적인 코딩에 사용하는 작업을 정해진 구조로 표현하는 방식이다. 이 표현은 참고[2] JD, PSEUDOCODE STANDARD의 표기 방식이다.
- COMPUTE express as targetName
- SET targetName to value
- STORE value in targetName
- INCREMENT targetName
- BUMP
- CALL functionName
- CALL functionName with ParameterNames seperated by comma
- CALL functionName RETURNING variable
- WHILE condition
sequence
END WHILE - IF condition THEN
sequence1
ELSE
sequece 2
END IF - REPEAT
sequence
UNTIL condition - FOR iteration bounds
sequence
END FOR - CASE expression OF
condition 1: sequence 1
condition 2: sequence 2
…
DEFAULT:
END CASE - BEGIN
sequence
EXCEPTION
WHEN type1
WHEN type2sequence 1
ENDsequence 2
이 외에 다양한 표기 방식이 있을 수 있다.
구조화된 언어 표기를 활용한 예를 보자.
Sample1
SET total to zero
REPEAT
READ Template
IF Temperature > Freezing THEN
INCREMENT total
END IF
UNTIL Temperature < zero
Print total
FOR X = 1 to 10
FOR Y = 1 to 10
IF gameBoard[X][Y] == 0
Do nothing
ELSE
CALL theCall(X, Y) (recursive method)
END IF
END FOR
END FOR
Sample2
SET moveCount to 1
FOR each row on the board
FOR each column on the board
IF gameBoard position (row, column) is occupied THEN
CALL findAdajacentTiles with row, column
INCREMENT moveCount
END IF
END FOR
END FOR
FOR all the number at the back of the array
SET Temp equal the addition of each number
IF > 9 THEN
get the remainder of the number divided by 10 to the index and carry the "1"
Decrement one
Do it again for numbers before the decimal
Sample3
SET Carry to 0
FOR each DigitPosition in Number from least significant to most significat
COMPUTE Total as sum of FirstNum[DigitPosition] and SecondNum[DigitPosition] and Carry
IF Total > 10 THEN
SET Carry to 1
SUBTRACT 10 from Total
ELSE
SET Carry to 0
END IF
STORE Total in Result[DigitPosition]
END FOR
IF Carry = 1 THEN
RAISE Overflow exception
END IF
결론
필자는 복잡한 문제가 실마리가 풀리지 않을 경우 의사코드 형태로 정리하면 생각이 정리되고 문제가 풀리는 경우가 있다. 또한 도 알고리즘 문제를 해결할 경우에 자주 활용한다. 바로 코드를 작성하기에는 시행착오가 너무 많고 코딩 과정에 다른 문제로 시간을 소모하기 때문에 의사코드를 활용하는게 효율적이다. 이글로 의사코드를 얼마나 잘 활용할지는 모르겠지만 여러분 개발에 도움이 되었으면 하네요. ospace.
참고
[1] Pseudocode 101, 2022.10.18, https://www.povertyactionlab.org/sites/default/files/research-resources/rr_datacleaning_Pseudocode.pdf
[2] JD, PSEUDOCODE STANDARD, https://users.csc.calpoly.edu/~jdalbey/SWE/pdl_std.html
[3] Basic Algorithm, https://www.cs.utexas.edu/users/mitra/csSummer2022/hsra/lectures/basic_algo.html
'2.분석 및 설계' 카테고리의 다른 글
The C10k Problem (4) | 2024.01.13 |
---|---|
CAP 이론 소개 (1) | 2023.11.20 |
glTF 포멧 (0) | 2023.06.08 |
[mybatis] Mybatis 내부동작 흐름 (0) | 2022.01.26 |
YUV 포멧 (0) | 2021.11.15 |