HanSol's Oak Cask

코딩 테스트에서 import 없이 해결할 수 있는 함수 대체 방법 정리 본문

알고리즘, 코딩테스트

코딩 테스트에서 import 없이 해결할 수 있는 함수 대체 방법 정리

HanSol_Lim 2025. 2. 11. 10:37

🚀 코딩 테스트에서 import 없이 해결할 수 있는 함수 대체 방법 정리

코딩 테스트 환경에서 import 없이도 기본 연산만으로 해결할 수 있도록 여러 함수들의 대체 방법을 정리했습니다.
이제 외부 모듈 없이도 다양한 기능을 구현할 수 있습니다! 🎯


1. math 모듈 대체 방법

기능 math 함수 대체 방법

올림 (ceil) math.ceil(a / b) (a + b - 1) // b
내림 (floor) math.floor(a / b) a // b
반올림 (round) round(x) int(x + 0.5) (양수일 때)
최대공약수(GCD) math.gcd(a, b) 유클리드 알고리즘 사용
최소공배수(LCM) math.lcm(a, b) a * b // gcd(a, b)
거듭제곱 math.pow(a, b) a ** b
제곱근 math.sqrt(a) a ** 0.5
절댓값 math.fabs(a) abs(a) (Python 기본 함수)
팩토리얼 math.factorial(n) 반복문 사용 (for i in range(1, n+1): res *= i)

2. itertools 모듈 대체 방법

기능 itertools 함수 대체 방법

순열 (permutations) itertools.permutations(lst) 백트래킹으로 직접 구현
조합 (combinations) itertools.combinations(lst, r) 백트래킹 or 비트마스크
중복순열 (product) itertools.product(lst, repeat=r) 다중 루프 사용
누적 합 (accumulate) itertools.accumulate(lst) prefix_sum[i] = prefix_sum[i-1] + lst[i]

3. random 모듈 대체 방법

기능 random 함수 대체 방법

난수 생성 random.randint(a, b) (seed * 1103515245 + 12345) % (b - a + 1) + a (LCG 알고리즘)
리스트 섞기 random.shuffle(lst) Fisher-Yates 알고리즘 사용
리스트에서 랜덤 선택 random.choice(lst) lst[random.randint(0, len(lst) - 1)]

4. collections 모듈 대체 방법

기능 collections 함수 대체 방법

카운터 (빈도수) collections.Counter(lst) 딕셔너리 활용 → count_dict = {}
기본값 딕셔너리 collections.defaultdict(int) count_dict.get(key, 0) + 1
덱 (deque) collections.deque() 리스트 사용, pop(0) 대신 슬라이싱 활용

5. bisect 모듈 대체 방법 (이진 탐색)

기능 bisect 함수 대체 방법

이진 탐색 (lower_bound) bisect.bisect_left(lst, x) 이진 탐색 직접 구현
이진 탐색 (upper_bound) bisect.bisect_right(lst, x) 이진 탐색 직접 구현

🔹 bisect_left 대체 코드 (이진 탐색)

def lower_bound(lst, x):
    left, right = 0, len(lst)
    while left < right:
        mid = (left + right) // 2
        if lst[mid] < x:
            left = mid + 1
        else:
            right = mid
    return left

6. heapq 모듈 대체 방법 (우선순위 큐)

기능 heapq 함수 대체 방법

최소 힙 heapq.heappush(heap, x) 리스트 append() 후 sort()
힙에서 최소값 추출 heapq.heappop(heap) min(heap), heap.remove(min(heap))

🔹 최소 힙 대체 코드

def heappush(heap, value):
    heap.append(value)
    heap.sort()  # 정렬된 상태 유지

def heappop(heap):
    return heap.pop(0)  # 최솟값을 추출

하지만, heapq 없이 구현하면 O(N log N)이므로, 속도가 느려질 수 있음.


7. 기타 기본 함수 대체 방법

기능 Python 기본 함수 대체 방법

문자열 공백 제거 s.strip() s.lstrip().rstrip()
문자열 대소문자 변환 s.upper() ''.join([chr(ord(c) - 32) if 'a' <= c <= 'z' else c for c in s])
문자열 정렬 sorted(s) ''.join(sorted(list(s)))
최대값 max(lst) sorted(lst)[-1]
최소값 min(lst) sorted(lst)[0]
리스트 뒤집기 lst[::-1] lst.reverse() (반환값 없음)
리스트 중복 제거 set(lst) list(dict.fromkeys(lst))
문자열 숫자로 변환 int(s) (ord(s[0]) - ord('0')) * 10 + (ord(s[1]) - ord('0'))

🎯 마무리

  • 코딩 테스트 환경에서 import 없이 해결할 수 있도록 위 방법들을 활용
  • 특히 math, itertools, collections, bisect, heapq 등의 함수 대체 방법을 익혀두면 문제 해결 속도가 빨라짐! 🚀