콘텐츠로 이동

파이썬 객관식 심화 — SET 15 (긴 코드·최고난도)

이름: ____________ 점수: _____ / 100 난이도: ★★★★★

다소 긴 프로그램입니다. 차분히 끝까지 추적하여 실행 결과를 고르세요. (문항당 10점, 범위: 1~8장 종합)


1. (중첩 while·런렝스 인코딩)

s = "aaabbbcccd"
result = ""
i = 0
while i < len(s):
    count = 1
    while i + 1 < len(s) and s[i] == s[i + 1]:
        count += 1
        i += 1
    result += s[i] + str(count)
    i += 1
print(result)

a3b3c3da3b3c3d1aaabbbcccda3b3c3d0Error

2. (약수 합·수 분류)

def classify(n):
    total = 0
    for i in range(1, n):
        if n % i == 0:
            total += i
    if total == n:
        return "perfect"
    elif total > n:
        return "abundant"
    return "deficient"

print(classify(6), classify(12), classify(8))

perfect deficient abundantabundant perfect deficientperfect abundant deficientperfect perfect deficientError

3. (while·뉴턴 제곱근)

x = 50
guess = x / 2
prev = 0
while abs(guess - prev) > 0.0001:
    prev = guess
    guess = (guess + x / guess) / 2
print(round(guess, 2))

7.07.0725.050.07.1

4. (2차원·행 합 최대)

matrix = [
    [3, 8, 2],
    [9, 1, 5],
    [4, 7, 6],
]
best_row = 0
best_sum = 0
for i in range(len(matrix)):
    row_sum = 0
    for x in matrix[i]:
        row_sum += x
    if row_sum > best_sum:
        best_sum = row_sum
        best_row = i
print(best_row, best_sum)

1 152 172 130 13Error

5. (재귀·하노이 탑 횟수)

def hanoi(n):
    if n == 1:
        return 1
    return 2 * hanoi(n - 1) + 1

print(hanoi(1), hanoi(3), hanoi(5))

1 7 251 7 311 6 301 8 32Error

6. (클래스·메서드 내부 while)

class Game:
    def __init__(self):
        self.score = 0
        self.level = 1
    def add_points(self, p):
        self.score += p
        while self.score >= self.level * 100:
            self.score -= self.level * 100
            self.level += 1

g = Game()
g.add_points(150)
g.add_points(120)
print(g.level, g.score)

2 1703 702 2701 270Error

7. (예외·여러 분기)

def calc(a, b, op):
    try:
        if op == "+":
            return a + b
        elif op == "/":
            return a / b
        elif op == "idx":
            return [a][b]
        else:
            raise ValueError("unknown")
    except ZeroDivisionError:
        return "div0"
    except IndexError:
        return "range"
    except ValueError:
        return "bad op"

print(calc(10, 0, "/"), calc(5, 2, "idx"), calc(1, 1, "?"))

div0 bad op rangediv0 range bad opinf range bad opdiv0 range unknownError

8. (모듈·소수 판별)

import math

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, math.floor(math.sqrt(n)) + 1):
        if n % i == 0:
            return False
    return True

count = 0
for n in range(2, 50):
    if is_prime(n):
        count += 1
print(count)

14151625Error

9. (리스트·두 정렬 리스트 병합)

a = [1, 4, 7, 9]
b = [2, 3, 8]
merged = []
i = 0
j = 0
while i < len(a) and j < len(b):
    if a[i] <= b[j]:
        merged.append(a[i])
        i += 1
    else:
        merged.append(b[j])
        j += 1
while i < len(a):
    merged.append(a[i])
    i += 1
while j < len(b):
    merged.append(b[j])
    j += 1
print(merged)

[1, 2, 3, 4, 7, 8, 9][1, 4, 7, 9, 2, 3, 8][1, 2, 3, 4, 7, 9, 8][1, 2, 3, 4, 8, 7, 9]Error

10. (종합·순위 매기기)

students = {"Kim": 85, "Lee": 92, "Park": 78, "Choi": 92, "Yoon": 85}
scores = []
for name in students:
    scores.append(students[name])
scores.sort(reverse=True)

ranks = {}
for name in students:
    rank = 1
    for s in scores:
        if s > students[name]:
            rank += 1
    ranks[name] = rank

print(ranks["Lee"], ranks["Kim"], ranks["Park"])

1 2 31 3 52 3 51 3 4Error