프로그램 CODE에서 쓰는 함수
이 사이트의 예제·모범 답안에 실제로 나오는 함수를 묶음별로 정리 (예의 결과는 실제 실행 값)
실기 문제 코드는 거의 같은 함수 몇십 개로 이루어집니다. 파일에서 문자열을 읽고(open, strip, split) → 숫자로 바꾸고(float, int) → 계산하고(numpy, math, heapq) → 형식에 맞춰 씁니다(f-문자열, write). 함수 이름과 인자 순서, 결과의 단위(도/라디안)를 정확히 알면 시험장에서 검색 없이 쓸 수 있습니다.
| 묶음 | 대표 함수 | 쓰는 곳 |
|---|---|---|
| 파일 · 출력 | open f.write print f"{v:.2f}" | 모든 문제의 입력·출력 |
| 형 변환 · 내장 | float int round range enumerate zip map | 입력 해석, 반복 |
| 문자열 | strip split replace join bytes.fromhex int.from_bytes | 줄 해석, CAN 프레임 |
| 리스트 · 딕셔너리 | append [::-1] get setdefault items | 경로 역추적, 그래프 |
| numpy | deg2rad cos sin arctan2 arccos clip @ linalg.solve | FK·IK·MK, 궤적, 동역학 |
| math · random | math.dist math.hypot random.seed random.uniform | 경로 길이, RRT*, 파티클 |
| heapq | heappush heappop | Dijkstra, A* |
| csv · pandas · openpyxl | csv.writer csv.DictReader pd.read_csv Workbook ScatterChart | 1-3 CSV 파일, 10 엑셀로 차트 그리기 |
np.cos,np.sin,math.cos는 라디안만 받습니다. 도 단위 입력은np.deg2rad먼저, 출력이 도면np.degrees로 되돌립니다.np.arctan2(y, x)는 y가 먼저입니다. 순서를 바꾸면 다른 각도가 나옵니다.int("45.5")는 오류입니다. 소수가 섞일 수 있으면float()로 읽고 필요할 때int().round()는 .5에 딱 걸리면 짝수 쪽으로 갑니다(round(0.5)= 0). 출력 자리수는f"{v:.2f}"로 맞추는 것이 안전합니다.split()(인자 없음)은 여러 칸 공백을 하나로 보지만,split(" ")은 빈 문자열이 생깁니다.range(a, b),np.arange(a, b)는 b를 포함하지 않습니다. 끝점까지 필요하면np.linspace.np.arccos에 1.0000001처럼 범위를 살짝 넘는 값이 들어가면 nan이 됩니다.np.clip(v, -1, 1)로 감쌉니다.np.clip(v, -1, 1)은 v를 −1과 1 사이로 잘라 내는 함수입니다.- 범위 안이면 값이 그대로 나옵니다.
- −1보다 작으면 −1, 1보다 크면 1로 바꿉니다.
heapq는 가장 작은 값이 먼저 나옵니다. 튜플은 첫 값으로 비교하므로, 의미가 있는 거리부터 해서(거리, 노드)순서로 넣습니다.
「→」 뒤의 결과는 모두 실제로 실행해서 나온 값이고, → 가 없는 줄은 사용 예입니다. 예에 쓴 변수: line = " 30 45.5 -10\n", row = "0.1,0.25,1.2", d = {"A": 0, "B": 3}, a = np.array([1.0, 2.0, 3.0]), M = [[2, 1], [1, 3]], b = [3, 5].
파일 · 화면 출력 · 모든 문제
| 함수 | 하는 일 | 예 → 결과 |
|---|---|---|
open(path, mode, encoding=…, newline=…) | 파일 열기. mode: "r" 읽기, "w" 새로 쓰기, "a" 이어 쓰기 | with open(p, "w", encoding="utf-8") as f: |
f.write(문자열) | 파일에 문자열 쓰기. 줄바꿈 \n은 직접 붙임 | f.write(f"{x:.2f} {y:.2f}\n") |
for line in f | 파일을 한 줄씩 읽기 (줄 끝 \n 포함) | for line in f: ... |
f.readline() / f.read() | 한 줄만 읽기 (머리글 건너뛰기) / 전체를 한 문자열로 | header = f.readline() |
print(값, sep=" ", end="\n") | 화면 출력. sep: 값 사이 글자, end: 끝 글자 | print('x', 1.5, sep=',')→ 화면: x,1.5 |
f"{값:형식}" | f-문자열 형식 지정. .2f 소수 2자리, 8.3f 폭 8, .3e 지수, 03d 0 채우기 | f'{3.14159:.2f}|{3.14159:8.3f}|{0.000123:.3e}|{7:03d}'→ '3.14| 3.142|1.230e-04|007' |
형 변환 · 기본 내장 함수 · 입력 해석, 반복
| 함수 | 하는 일 | 예 → 결과 |
|---|---|---|
float(s) / int(s) / str(v) | 문자열 ↔ 숫자 변환 | float('45.5'), int('7'), str(0.5)→ (45.5, 7, '0.5') |
round(v, n) | 소수 n자리 반올림. 정확히 .5이면 짝수 쪽으로 감(2.5 → 2, 3.5 → 4) | round(3.14159, 2), round(2.5), round(3.5)→ (3.14, 2, 4) |
abs(v) | 절댓값 | abs(-3.2)→ 3.2 |
len(x) | 개수 | len([10, 20, 30])→ 3 |
range(시작, 끝, 간격) | 정수 나열. 끝은 포함 안 함 | list(range(0, 10, 3))→ [0, 3, 6, 9] |
enumerate(x) | (번호, 값) 짝으로 반복 | list(enumerate(['a', 'b']))→ [(0, 'a'), (1, 'b')] |
zip(x, y) | 두 목록을 같은 위치끼리 짝지음 | list(zip([1, 2], ['a', 'b']))→ [(1, 'a'), (2, 'b')] |
map(함수, x) | 모든 값에 함수 적용 | list(map(float, ['1', '2.5']))→ [1.0, 2.5] |
sum / max / min / sorted | 합계 / 최댓값 / 최솟값 / 정렬한 새 목록 | sum([1, 2, 3]), max([4, 9, 2]), min([4, 9, 2]), sorted([3, 1, 2])→ (6, 9, 2, [1, 2, 3]) |
chr(n) / ord(c) | 코드 번호 ↔ 글자 | chr(65), ord('A')→ ('A', 65) |
next(반복자) | 다음 값 하나 꺼내기 (csv 머리글 건너뛰기) | header = next(reader) |
문자열 처리 · 줄 해석, 통신 프레임
| 함수 | 하는 일 | 예 → 결과 |
|---|---|---|
s.strip() | 앞뒤 공백과 줄바꿈 제거 | line.strip()→ '30 45.5 -10' |
s.split() / s.split(",") | 공백(여러 칸도 하나로) / 쉼표 기준으로 나누기 | line.split(), row.split(',')→ (['30', '45.5', '-10'], ['0.1', '0.25', '1.2']) |
s.replace(a, b) | a를 b로 바꾸기 (쉼표·공백 섞인 입력 통일) | row.replace(',', ' ').split()→ ['0.1', '0.25', '1.2'] |
s.startswith(t) | t로 시작하는지 (주석 # 줄 거르기) | '# 주석'.startswith('#')→ True |
"구분자".join(목록) | 문자열 목록을 구분자로 이어 붙이기 | ' '.join(['0.68', '1.18'])→ '0.68 1.18' |
s.upper() | 대문자로 | 't200'.upper()→ 'T200' |
s.encode(인코딩) / b.decode(인코딩) | 문자열 ↔ 바이트 | '열'.encode('utf-8').hex(' '), bytes.fromhex('ec 97 b4').decode('utf-8')→ ('ec 97 b4', '열') |
bytes.fromhex(s) / b.hex() | 16진수 문자열 ↔ 바이트 (CAN 데이터) | list(bytes.fromhex('10 27')), bytes([16, 39]).hex(' ')→ ([16, 39], '10 27') |
int.from_bytes(b, "little") / n.to_bytes(2, "little") | 바이트 ↔ 정수. little: 낮은 바이트가 앞 | int.from_bytes(bytes([16, 39]), 'little'), (10000).to_bytes(2, 'little').hex(' ')→ (10000, '10 27') |
리스트 · 딕셔너리 · 경로, 그래프
| 함수 | 하는 일 | 예 → 결과 |
|---|---|---|
x.append(v) | 목록 끝에 추가 | path.append(node) |
x.reverse() / x[::-1] | 목록 뒤집기 (역추적한 경로를 출발→도착 순서로) | [3, 2, 1][::-1]→ [1, 2, 3] |
d.get(k, 기본값) | 키가 없으면 기본값 | d.get('B', 99), d.get('Z', 99)→ (3, 99) |
d.setdefault(k, []) | 키가 없으면 만들고 값을 돌려줌 (그래프 인접 목록 만들 때) | graph.setdefault(u, []).append((v, w)) |
d.items() / d.values() | (키, 값) 짝 / 값만 반복 | list(d.items())→ [('A', 0), ('B', 3)] |
numpy (np) · 기구학, 궤적, 동역학
| 함수 | 하는 일 | 예 → 결과 |
|---|---|---|
np.array(목록) | 숫자 배열 만들기. 배열끼리 + − × 가 원소별로 됨 | a * 2→ [2., 4., 6.] |
np.deg2rad / np.rad2deg (= np.radians / np.degrees) | 도 ↔ 라디안 | np.deg2rad(180), np.degrees(np.pi / 2)→ (3.141593, 90.0) |
np.cos / np.sin | 삼각함수. 입력은 라디안 | np.cos(np.deg2rad(60))→ 0.5 |
np.arctan2(y, x) | 사분면까지 구분하는 각도 (y가 먼저). np.atan2도 같은 함수지만 numpy 2.0부터만 있음 | np.degrees(np.arctan2(1, -1))→ 135.0 |
np.arccos(v) | 역코사인. v는 −1~1이어야 함. np.acos(v)는 numpy 2.0부터 생긴 같은 함수(별칭)라 1.x에서는 오류 → 버전과 상관없는 np.arccos 사용 | np.degrees(np.arccos(0.5))→ 60.0 |
np.clip(v, 최소, 최대) | 범위 밖 값을 경계로 자름 (arccos 인자, 출력 포화) | np.clip(1.0000001, -1, 1)→ 1.0 |
np.hypot(x, y) / np.sqrt(v) | √(x² + y²) / 제곱근 | np.hypot(3, 4), np.sqrt(2)→ (5.0, 1.414214) |
np.round(v, n) | 배열 반올림 | np.round(np.array([1.23456, 2.71828]), 3)→ [1.235, 2.718] |
np.linspace(a, b, n) / np.arange(a, b, step) | a~b를 n개로 / step 간격 (b 미포함) | np.linspace(0, 1, 5), np.arange(0, 1, 0.25)→ ([0. , 0.25, 0.5 , 0.75, 1. ], [0. , 0.25, 0.5 , 0.75]) |
np.zeros(n) | 0으로 채운 배열 (결과를 담을 빈 배열 만들 때) | np.zeros(3)→ [0., 0., 0.] |
np.eye(n) | n×n 단위 행렬 (대각선 1, 나머지 0). DH 변환행렬 곱의 시작값 T = np.eye(4), 뉴턴-랩슨의 단위 행렬 등에 사용 | np.eye(3)→ [[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]] |
np.cumsum(x) / np.sum(x) | 누적 합 / 합 | np.cumsum([30, 30, 30])→ [30, 60, 90] |
np.sign(v) | 부호 (−1, 0, 1) | np.sign([-2.5, 0, 4])→ [-1., 0., 1.] |
A @ B | 행렬 곱 (자코비안 × 관절 속도) | M @ np.array([1.0, 1.0])→ [3., 4.] |
np.linalg.solve(A, b) | A·x = b 풀기 (역행렬보다 정확) | np.linalg.solve(M, b)→ [0.8, 1.4] |
np.linalg.det(A) / np.linalg.norm(v) | 행렬식 (0이면 특이점) / 벡터 크기 | np.linalg.det(M), np.linalg.norm([3, 4])→ (5.0, 5.0) |
math · random · 경로 길이, RRT*, 파티클
| 함수 | 하는 일 | 예 → 결과 |
|---|---|---|
math.sqrt / math.hypot / math.dist(p, q) | 제곱근 / √(x²+y²) / 두 점 사이 거리 | math.dist((0, 0), (3, 4))→ 5.0 |
math.radians / math.cos / math.sin | numpy 없이 쓰는 같은 기능 (숫자 하나만) | math.cos(math.radians(60))→ 0.5 |
math.floor(v) / math.exp(v) / math.log(v) | 내림 / eˣ / 자연로그 | math.floor(-1.5), math.exp(1), math.log(math.e)→ (-2, 2.718282, 1.0) |
random.seed(n) | 난수 시작점 고정 → 실행할 때마다 같은 결과 | random.seed(1) |
random.random() / random.uniform(a, b) | 0~1 / a~b 사이 난수 | x = random.uniform(0, 100) |
heapq (우선순위 큐) · Dijkstra, A*
| 함수 | 하는 일 | 예 → 결과 |
|---|---|---|
heapq.heappush(h, (거리, 노드)) | 넣기. 튜플은 첫 값(거리) 기준으로 정렬됨 | heapq.heappush(h, (5, 'B')) |
heapq.heappop(h) | 가장 작은 값 꺼내기. (5,B) (2,A) (7,C)를 넣었다면 | heapq.heappop(h)→ (2, 'A') |
자주 쓰는 함수를 한 파일에서 실행해 보는 예제입니다. 결과를 눈으로 확인하며 함수 동작을 익힙니다.
# 실기 코드에서 자주 쓰는 함수 실행해 보기
import math
import heapq
import numpy as np
# 1) 문자열 → 숫자 : strip, split, replace, float, map
line = " 30 45.5 -10\n"
vals = [float(v) for v in line.strip().split()]
print("1) split + float :", vals)
row = "0.1,0.25,1.2"
print(" 쉼표 입력 :", list(map(float, row.replace(",", " ").split())))
# 2) 형식 출력 : f-문자열
x, y = 0.683013, 1.183013
print(f"2) f-문자열 : {x:.2f} {y:.2f} | {x:8.3f} | {0.000123:.3e} | {7:03d}")
# 3) 도 ↔ 라디안, 삼각함수
th = np.deg2rad(60)
print(f"3) cos 60° : {np.cos(th):.4f} (np.cos(60) = {np.cos(60):.4f} ← 라디안으로 착각한 값)")
# 4) arctan2 : 사분면 구분
print(f"4) arctan2(1, -1) : {np.degrees(np.arctan2(1, -1)):.1f}° atan(1/-1) = {np.degrees(np.arctan(1 / -1)):.1f}°")
# 5) arccos + clip
c = 1.0000001
print("5) arccos(1.0000001):", np.arccos(c) if abs(c) <= 1 else "nan (범위 밖)",
"→ clip 후", np.degrees(np.arccos(np.clip(c, -1, 1))))
# 6) 거리
print("6) hypot / dist :", np.hypot(3, 4), math.dist((0, 0), (3, 4)))
# 7) 행렬 : @, solve
M = np.array([[2.0, 1.0], [1.0, 3.0]])
b = np.array([3.0, 5.0])
sol = np.linalg.solve(M, b)
print("7) solve(M, b) :", sol, " 검산 M @ x =", M @ sol)
# 8) heapq : 가장 작은 거리부터
h = []
for item in [(5, "B"), (2, "A"), (7, "C")]:
heapq.heappush(h, item)
print("8) heappop 순서 :", [heapq.heappop(h) for _ in range(3)])
# 9) 경로 역추적 후 뒤집기
parent = {"D": "C", "C": "A", "A": None}
path, node = [], "D"
while node is not None:
path.append(node)
node = parent.get(node)
print("9) 경로 :", "-".join(path[::-1]))
# 10) 바이트 ↔ 정수 (CAN)
data = bytes.fromhex("10 27 05 00")
rpm = int.from_bytes(data[0:2], "little")
print("10) CAN 바이트 :", data.hex(" "), "→ rpm =", rpm)# Run the functions often used in the practical-exam code
import math
import heapq
import numpy as np
# 1) string → number : strip, split, replace, float, map
line = " 30 45.5 -10\n"
vals = [float(v) for v in line.strip().split()]
print("1) split + float :", vals)
row = "0.1,0.25,1.2"
print(" comma input :", list(map(float, row.replace(",", " ").split())))
# 2) formatted output : f-string
x, y = 0.683013, 1.183013
print(f"2) f-string : {x:.2f} {y:.2f} | {x:8.3f} | {0.000123:.3e} | {7:03d}")
# 3) degrees ↔ radians, trigonometric functions
th = np.deg2rad(60)
print(f"3) cos 60° : {np.cos(th):.4f} (np.cos(60) = {np.cos(60):.4f} ← value mistaken as radians)")
# 4) arctan2 : tells the quadrant
print(f"4) arctan2(1, -1) : {np.degrees(np.arctan2(1, -1)):.1f}° atan(1/-1) = {np.degrees(np.arctan(1 / -1)):.1f}°")
# 5) arccos + clip
c = 1.0000001
print("5) arccos(1.0000001):", np.arccos(c) if abs(c) <= 1 else "nan (out of range)",
"→ after clip", np.degrees(np.arccos(np.clip(c, -1, 1))))
# 6) distance
print("6) hypot / dist :", np.hypot(3, 4), math.dist((0, 0), (3, 4)))
# 7) matrix : @, solve
M = np.array([[2.0, 1.0], [1.0, 3.0]])
b = np.array([3.0, 5.0])
sol = np.linalg.solve(M, b)
print("7) solve(M, b) :", sol, " check M @ x =", M @ sol)
# 8) heapq : smallest distance first
h = []
for item in [(5, "B"), (2, "A"), (7, "C")]:
heapq.heappush(h, item)
print("8) heappop order :", [heapq.heappop(h) for _ in range(3)])
# 9) backtrack the path, then reverse
parent = {"D": "C", "C": "A", "A": None}
path, node = [], "D"
while node is not None:
path.append(node)
node = parent.get(node)
print("9) path :", "-".join(path[::-1]))
# 10) bytes ↔ integer (CAN)
data = bytes.fromhex("10 27 05 00")
rpm = int.from_bytes(data[0:2], "little")
print("10) CAN bytes :", data.hex(" "), "→ rpm =", rpm)1) split + float : [30.0, 45.5, -10.0] 쉼표 입력 : [0.1, 0.25, 1.2] 2) f-문자열 : 0.68 1.18 | 0.683 | 1.230e-04 | 007 3) cos 60° : 0.5000 (np.cos(60) = -0.9524 ← 라디안으로 착각한 값) 4) arctan2(1, -1) : 135.0° atan(1/-1) = -45.0° 5) arccos(1.0000001): nan (범위 밖) → clip 후 0.0 6) hypot / dist : 5.0 5.0 7) solve(M, b) : [0.8 1.4] 검산 M @ x = [3. 5.] 8) heappop 순서 : [(2, 'A'), (5, 'B'), (7, 'C')] 9) 경로 : A-C-D 10) CAN 바이트 : 10 27 05 00 → rpm = 10000
1) split + float : [30.0, 45.5, -10.0] comma input : [0.1, 0.25, 1.2] 2) f-string : 0.68 1.18 | 0.683 | 1.230e-04 | 007 3) cos 60° : 0.5000 (np.cos(60) = -0.9524 ← value mistaken as radians) 4) arctan2(1, -1) : 135.0° atan(1/-1) = -45.0° 5) arccos(1.0000001): nan (out of range) → after clip 0.0 6) hypot / dist : 5.0 5.0 7) solve(M, b) : [0.8 1.4] check M @ x = [3. 5.] 8) heappop order : [(2, 'A'), (5, 'B'), (7, 'C')] 9) path : A-C-D 10) CAN bytes : 10 27 05 00 → rpm = 10000