콘텐츠로 이동

파이썬 객관식 심화 — SET 12 (긴 코드)

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

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


1. (문자열 처리)

words = ["apple", "banana", "kiwi", "cherry"]
result = ""
for w in words:
    if len(w) >= 5:
        result += w[0] + w[-1]
print(result)

aebakicyaekicyaebacyaebacabc

2. (조건·집계)

fizz = 0
buzz = 0
both = 0
for i in range(1, 51):
    if i % 3 == 0 and i % 5 == 0:
        both += 1
    elif i % 3 == 0:
        fizz += 1
    elif i % 5 == 0:
        buzz += 1
print(fizz, buzz, both)

13 7 316 10 313 7 010 13 316 10 0

3. (while·유클리드 호제법)

a = 48
b = 36
while b != 0:
    a, b = b, a % b
print(a)

6123641

4. (2차원 인덱싱)

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]
diag = 0
anti = 0
n = len(matrix)
for i in range(n):
    diag += matrix[i][i]
    anti += matrix[i][n - 1 - i]
print(diag, anti)

15 1515 1745 4515 1312 15

5. (재귀·자릿수 합)

def digit_sum(n):
    if n < 10:
        return n
    return n % 10 + digit_sum(n // 10)

print(digit_sum(9875))

2029987519Error

6. (클래스 변수 + 인스턴스 변수)

class Quiz:
    total_questions = 0
    def __init__(self, name):
        self.name = name
        self.correct = 0
    def answer(self, is_right):
        Quiz.total_questions += 1
        if is_right:
            self.correct += 1
    def rate(self):
        return self.correct

a = Quiz("A")
b = Quiz("B")
a.answer(True)
a.answer(False)
a.answer(True)
b.answer(True)
print(a.rate(), b.rate(), Quiz.total_questions)

2 1 43 1 42 1 32 1 23 1 3

7. (예외 처리)

def process(data):
    results = []
    for pair in data:
        a, b = pair
        try:
            results.append(a / b)
        except ZeroDivisionError:
            results.append("inf")
    return results

print(process([(10, 2), (5, 0), (9, 3)]))

[5.0, 'inf', 3.0][5, 'inf', 3][5.0, 0, 3.0]['inf', 5.0, 3.0]Error

8. (모듈·math)

import math

def is_perfect_square(n):
    root = math.sqrt(n)
    return math.floor(root) == root

count = 0
for n in range(1, 30):
    if is_perfect_square(n):
        count += 1
print(count)

45629Error

9. (딕셔너리·재고)

inventory = {"apple": 5, "banana": 3}
orders = [("apple", 2), ("banana", 5), ("cherry", 1), ("apple", 1)]
rejected = 0
for item, qty in orders:
    if item in inventory and inventory[item] >= qty:
        inventory[item] -= qty
    else:
        rejected += 1
print(inventory["apple"], rejected)

2 12 23 22 3Error

10. (종합·개표)

votes = ["A", "B", "A", "C", "B", "A", "C", "C", "C"]
tally = {}
for v in votes:
    tally[v] = tally.get(v, 0) + 1

winner = ""
high = 0
tie = False
for c in tally:
    if tally[c] > high:
        high = tally[c]
        winner = c
        tie = False
    elif tally[c] == high:
        tie = True

print(winner, high, tie)

C 4 FalseC 4 TrueA 3 FalseC 9 FalseError