파이썬 객관식 심화 — 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)
① aebakicy ② aekicy ③ aebacy ④ aebac ⑤ abc
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 3 ② 16 10 3 ③ 13 7 0 ④ 10 13 3 ⑤ 16 10 0
3. (while·유클리드 호제법)¶
a = 48
b = 36
while b != 0:
a, b = b, a % b
print(a)
① 6 ② 12 ③ 36 ④ 4 ⑤ 1
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 15 ② 15 17 ③ 45 45 ④ 15 13 ⑤ 12 15
5. (재귀·자릿수 합)¶
def digit_sum(n):
if n < 10:
return n
return n % 10 + digit_sum(n // 10)
print(digit_sum(9875))
① 20 ② 29 ③ 9875 ④ 19 ⑤ Error
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 4 ② 3 1 4 ③ 2 1 3 ④ 2 1 2 ⑤ 3 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)
① 4 ② 5 ③ 6 ④ 29 ⑤ Error
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 1 ② 2 2 ③ 3 2 ④ 2 3 ⑤ Error
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 False ② C 4 True ③ A 3 False ④ C 9 False ⑤ Error