본문 바로가기

장 실습: polyphase 파일 정렬을 세 단계로 검사하기

파일 정렬의 결과와 단계별 런 상태를 고정 입력·무작위 입력으로 검사합니다.

파일로 정렬 결과가 나와도 값이 빠지거나 같은 값을 두 번 쓸 수 있습니다. 이 장에서 만든 polyphase_sort_file을 고정 입력, 무작위 입력, 단계별 성질의 세 가지 방법으로 검사합니다.

이 글을 마치면 다음을 할 수 있습니다.

  • 파일 정렬의 결과와 단계별 런 상태를 고정 입력·무작위 입력으로 검사합니다.
  • 마지막 런 수와 병합한 값의 수를 확인해 단계별 성질을 검사합니다.

시작 상태

세 파일 polyphase 병합의 polyphase.py에서 함수 정의는 남기고 맨 아래의 실행용 with TemporaryDirectory() as folder: 블록만 지웁니다. 외부 정렬 글의 연습 문제 4에 있는 check_file_sort도 준비합니다. 아래 완성 파일에는 필요한 함수를 모두 모았습니다. Python 설치나 명령 실행이 준비되지 않았다면 1장 첫 글부터 확인합니다. 이 실습은 표준 라이브러리만 사용하므로 추가 패키지 설치는 없습니다.

파일이 있는 폴더에서 다음 명령으로 실행합니다. 단계마다 저장한 뒤 같은 명령을 사용합니다.

python polyphase.py

단계별로 만들고 확인하기

1단계: 경계 사례. [], [4], [5, 2, 8], [5, 2, 8, 1], [4, 3, 2, 1], 앞 글의 일곱 값을 각각 청크 크기 3, 3, 5, 2, 1, 1로 정렬하고, 입력과 청크 크기, report["initial"], 가상 런 수, 단계 수, 결과가 sorted(입력)과 같은지를 한 줄씩 출력합니다. 실행하기 전에 처음 분배와 가상 런 수, 단계 수를 손으로 구해 보세요.

2단계: 무작위 대조. 외부 정렬 글 연습 문제 4의 check_file_sort를 그대로 붙여 넣고 polyphase_sort_file을 검사합니다. 203개 입력 통과가 나오면 성공입니다.

3단계: 단계마다의 성질. 앞 글에서 설명한 성질이 실제로 지켜지는지 check_phases(trials=200, seed=7)로 확인합니다. 값 240개, 청크 크기 15인 무작위 입력마다 다음을 assert로 검사하고, 검사한 입력의 수를 돌려줍니다.

  • 어느 단계에서도 병합한 값의 개수가 전체 값의 개수 N을 넘지 않습니다.
  • 단계가 있다면 마지막 단계 뒤에는 한 파일에만 런이 1개 남고, 마지막 단계에서 병합한 값은 N개입니다.

힌트: report["phases"][-1]이 마지막 단계의 (런 수, 병합한 값의 개수)입니다. 런이 하나뿐이면 단계가 없으니 if report["phases"]:로 건너뛰고, 한 파일에만 런 1개가 남았는지는 sorted(런 수) == [0, 0, 1]로 확인합니다.

체크포인트

단계확인할 결과
1단계: 여섯 고정 입력여섯 줄의 마지막 값이 모두 True이고 처음 런 분배·가상 런·단계 수가 예상과 같습니다.
2단계: 무작위 대조203개 입력 통과가 출력됩니다.
3단계: 단계별 성질200개 입력에서 단계 성질 확인이 출력됩니다.

다를 때 먼저 볼 곳

증상먼저 볼 곳
값이 몇 개 빠진다_chunks의 마지막 if chunk:, 마지막 복사 반복
같은 값이 두 번 나온다병합 반복의 seek, 단계 끝의 tell() 저장
"런 파일이 중간에 끝났습니다" 오류가 난다_merge_one_run이 길이 줄만큼만 읽는지
3단계의 마지막 값 개수가 N보다 작다출력 파일을 counts.index(0)으로 골랐는지
완성 파일 전체와 확인 결과
polyphase.py
from pathlib import Path
from tempfile import TemporaryDirectory
import random

def _chunks(source, size):
    with source.open(encoding="utf-8") as stream:
        chunk = []
        for line in stream:
            chunk.append(int(line))
            if len(chunk) == size:
                yield sorted(chunk)
                chunk = []
        if chunk:
            yield sorted(chunk)

def _write_run(stream, values):
    stream.write(f"{len(values)}\n")
    for value in values:
        stream.write(f"{value}\n")

def _read_integer(stream):
    line = stream.readline()
    if not line:
        raise ValueError("런 파일이 중간에 끝났습니다")
    return int(line)

def _merge_one_run(left, right, output):
    left_count, right_count = _read_integer(left), _read_integer(right)
    length = left_count + right_count
    output.write(f"{length}\n")
    first = _read_integer(left) if left_count else None
    second = _read_integer(right) if right_count else None
    while first is not None or second is not None:
        if second is None or (first is not None and first <= second):
            output.write(f"{first}\n")
            left_count -= 1
            first = _read_integer(left) if left_count else None
        else:
            output.write(f"{second}\n")
            right_count -= 1
            second = _read_integer(right) if right_count else None
    return length

def fibonacci_counts(real_runs):
    if real_runs <= 1:
        return [real_runs, 0, 0]
    large, small = 1, 1
    while large + small < real_runs:
        large, small = large + small, large
    return [large, small, 0]

def polyphase_sort_file(source, destination, chunk_size):
    source, destination = Path(source), Path(destination)
    if type(chunk_size) is not int or chunk_size < 1:
        raise ValueError("청크 크기는 1 이상인 정수여야 합니다")
    if source.resolve() == destination.resolve():
        raise ValueError("원본을 덮어쓰지 않도록 출력 경로를 다르게 정해야 합니다")
    with source.open(encoding="utf-8") as stream:
        value_count = sum(1 for _ in stream)
    real_runs = (value_count + chunk_size - 1) // chunk_size
    counts = fibonacci_counts(real_runs)
    dummy_runs = sum(counts) - real_runs
    report = {"initial": counts.copy(), "dummy": dummy_runs, "phases": []}
    with TemporaryDirectory() as folder:
        paths = [Path(folder) / f"F{index}.txt" for index in range(3)]
        runs = _chunks(source, chunk_size)
        for index in range(3):
            with paths[index].open("w", encoding="utf-8") as stream:
                for slot in range(counts[index]):
                    if index == 0 and slot < dummy_runs:
                        _write_run(stream, [])
                    else:
                        _write_run(stream, next(runs))
        leftover = next(runs, None)
        runs.close()
        if leftover is not None:
            raise ValueError("두 번 읽는 사이에 원본 파일이 바뀌었습니다")
        offsets = [0, 0, 0]
        while sum(count > 0 for count in counts) > 1:
            first, second = [index for index, count in enumerate(counts) if count > 0]
            output_index = counts.index(0)
            pairs = min(counts[first], counts[second])
            moved = 0
            with paths[first].open(encoding="utf-8") as left, \
                    paths[second].open(encoding="utf-8") as right, \
                    paths[output_index].open("w", encoding="utf-8") as output:
                left.seek(offsets[first])
                right.seek(offsets[second])
                for _ in range(pairs):
                    moved += _merge_one_run(left, right, output)
                offsets[first], offsets[second] = left.tell(), right.tell()
            offsets[output_index] = 0
            counts[first] -= pairs
            counts[second] -= pairs
            counts[output_index] = pairs
            report["phases"].append((counts.copy(), moved))
        with destination.open("w", encoding="utf-8") as output:
            if real_runs > 0:
                final_index = next(index for index, count in enumerate(counts) if count > 0)
                with paths[final_index].open(encoding="utf-8") as stream:
                    stream.seek(offsets[final_index])
                    for _ in range(_read_integer(stream)):
                        output.write(f"{_read_integer(stream)}\n")
    return report

def check_file_sort(sort_file, trials=200, seed=2026):
    rng = random.Random(seed)
    cases = [[], [5], [3, 3, 3]]
    cases += [[rng.randint(-20, 20) for _ in range(rng.randint(0, 30))] for _ in range(trials)]
    with TemporaryDirectory() as folder:
        source = Path(folder) / "input.txt"
        destination = Path(folder) / "output.txt"
        for values in cases:
            chunk_size = rng.randint(1, 8)
            source.write_text("".join(f"{value}\n" for value in values), encoding="utf-8")
            sort_file(source, destination, chunk_size)
            result = [int(line) for line in destination.read_text(encoding="utf-8").split()]
            assert result == sorted(values), (values, chunk_size, result)
    return len(cases)

cases = [([], 3), ([4], 3), ([5, 2, 8], 5), ([5, 2, 8, 1], 2), ([4, 3, 2, 1], 1), ([8, 1, 6, 2, 9, 3, 7], 1)]
with TemporaryDirectory() as folder:
    source = Path(folder) / "input.txt"
    destination = Path(folder) / "output.txt"
    for values, chunk_size in cases:
        source.write_text("".join(f"{value}\n" for value in values), encoding="utf-8")
        report = polyphase_sort_file(source, destination, chunk_size)
        result = [int(line) for line in destination.read_text(encoding="utf-8").split()]
        print(values, chunk_size, report["initial"], report["dummy"], len(report["phases"]), result == sorted(values))

def check_phases(trials=200, seed=7):
    rng = random.Random(seed)
    with TemporaryDirectory() as folder:
        source = Path(folder) / "input.txt"
        destination = Path(folder) / "output.txt"
        for _ in range(trials):
            values = [rng.randint(0, 99) for _ in range(rng.randint(2, 40))]
            chunk_size = rng.randint(1, 5)
            source.write_text("".join(f"{value}\n" for value in values), encoding="utf-8")
            report = polyphase_sort_file(source, destination, chunk_size)
            for counts, moved in report["phases"]:
                assert moved <= len(values), (values, chunk_size, report)
            if report["phases"]:
                last_counts, last_moved = report["phases"][-1]
                assert sorted(last_counts) == [0, 0, 1], (values, chunk_size, report)
                assert last_moved == len(values), (values, chunk_size, report)
    return trials

print(f"{check_file_sort(polyphase_sort_file)}개 입력 통과")
print(f"{check_phases()}개 입력에서 단계 성질 확인")
[] 3 [0, 0, 0] 0 0 True
[4] 3 [1, 0, 0] 0 0 True
[5, 2, 8] 5 [1, 0, 0] 0 0 True
[5, 2, 8, 1] 2 [1, 1, 0] 0 1 True
[4, 3, 2, 1] 1 [3, 2, 0] 1 3 True
[8, 1, 6, 2, 9, 3, 7] 1 [5, 3, 0] 1 4 True

런 수는 (값의 개수 + 청크 크기 - 1) // 청크 크기이고, 런이 0개나 1개이면 단계가 없습니다. [5, 2, 8, 1]은 런 [2, 5], [1, 8]을 1과 1로 나누어 한 단계에 끝납니다. [4, 3, 2, 1]은 런 4개를 3과 2로 나누고 가상 런 1개를 넣어, F0이 ∅, [4], [3], F1이 [2], [1]로 시작합니다. 런 수는 3, 2, 0 → 1, 0, 2 → 0, 1, 1 → 1, 0, 0으로 바뀌며 [2], [1, 4], [2, 3], [1, 2, 3, 4]가 차례로 만들어집니다.

1단계의 여섯 줄 뒤에 다음 두 줄이 나오면 끝입니다.

203개 입력 통과
200개 입력에서 단계 성질 확인

check_file_sort는 한 글자도 바꾸지 않았습니다. 두 파일 정렬 함수의 모양을 (source, destination, chunk_size)로 맞춰 두었기 때문입니다. 3단계의 마지막 assert는 마지막 단계에서 런이 하나로 합쳐지므로 두 입력 런이 모든 값을 담고 있어야 한다는 뜻이고, 가상 런은 값이 없어 이 개수에 영향을 주지 않습니다.

더 해 보기

  • report에 단계마다 읽은 값과 쓴 값을 따로 기록하고 앞 글의 예에서 합계가 각각 21인지 확인합니다.
  • 작업 파일을 네 개로 늘린다면 런을 어떤 개수로 나누어 담을지 손으로 정합니다.

다음 장의 종합: 지도 요구에서 경로와 검사까지에서는 지금까지 배운 알고리즘을 하나의 문제에 함께 적용하고, 이 장에서 되풀이한 것처럼 빠른 방법을 느린 기준 구현과 무작위 입력으로 대조합니다.