파이썬 객관식 심화 — SET 13 (긴 코드)¶
이름: ____________ 점수: _____ / 100 난이도: ★★★★★
다소 긴 프로그램입니다. 차분히 끝까지 추적하여 실행 결과를 고르세요. (문항당 10점, 범위: 1~8장 종합)
1. (문자열 파싱)¶
raw = "12,34,56,78"
parts = raw.split(",")
total = 0
for p in parts:
total += int(p)
print(total, len(parts))
① 180 4 ② 180 7 ③ 12345678 4 ④ 180 1 ⑤ Error
2. (조건·윤년)¶
def is_leap(y):
if y % 400 == 0:
return True
if y % 100 == 0:
return False
if y % 4 == 0:
return True
return False
years = [2000, 1900, 2024, 2023]
count = 0
for y in years:
if is_leap(y):
count += 1
print(count)
① 1 ② 2 ③ 3 ④ 4 ⑤ Error
3. (while·이분 탐색)¶
secret = 42
low = 1
high = 100
guesses = 0
while low <= high:
mid = (low + high) // 2
guesses += 1
if mid == secret:
break
elif mid < secret:
low = mid + 1
else:
high = mid - 1
print(mid, guesses)
① 42 6 ② 42 7 ③ 42 50 ④ 50 7 ⑤ 42 8
4. (중첩 for·조건)¶
count = 0
n = 5
for i in range(1, n + 1):
for j in range(1, n + 1):
if i + j <= n:
count += 1
print(count)
① 10 ② 15 ③ 6 ④ 25 ⑤ 20
5. (재귀·빠른 거듭제곱)¶
def power(base, exp):
if exp == 0:
return 1
if exp % 2 == 0:
half = power(base, exp // 2)
return half * half
return base * power(base, exp - 1)
print(power(2, 10))
① 512 ② 1024 ③ 100 ④ 20 ⑤ Error
6. (클래스·여러 메서드)¶
class Sensor:
def __init__(self):
self.readings = []
def record(self, temp):
self.readings.append(temp)
def max_reading(self):
return max(self.readings)
def above(self, threshold):
count = 0
for r in self.readings:
if r > threshold:
count += 1
return count
s = Sensor()
for t in [20, 25, 30, 22, 28]:
s.record(t)
print(s.max_reading(), s.above(24))
① 30 3 ② 30 2 ③ 28 3 ④ 30 4 ⑤ Error
7. (예외·여러 종류) 다음 코드의 세 줄 출력으로 옳은 것은?¶
def safe_get(lst, idx, key):
try:
d = lst[idx]
return d[key]
except IndexError:
return "no index"
except KeyError:
return "no key"
data = [{"a": 1}, {"b": 2}]
print(safe_get(data, 0, "a"))
print(safe_get(data, 5, "a"))
print(safe_get(data, 1, "a"))
① 1 / no index / no key
② 1 / no key / no index
③ no index / 1 / no key
④ 1 / no index / no index
⑤ Error
8. (모듈·표준편차)¶
import math
def std_dev(nums):
mean = sum(nums) / len(nums)
var = 0
for n in nums:
var += (n - mean) ** 2
var = var / len(nums)
return math.sqrt(var)
print(std_dev([2, 4, 4, 4, 5, 5, 7, 9]))
① 4.0 ② 2.0 ③ 2 ④ 1.41 ⑤ Error
9. (리스트·순서 보존 중복 제거)¶
nums = [3, 1, 3, 2, 1, 4, 2, 5]
seen = []
result = []
for n in nums:
if n not in seen:
seen.append(n)
result.append(n)
print(result)
① [3, 1, 2, 4, 5] ② [1, 2, 3, 4, 5] ③ [3, 1, 3, 2, 1, 4, 2, 5] ④ [5, 4, 2, 1, 3] ⑤ [1, 3, 2, 4, 5]
10. (종합·장바구니)¶
prices = {"pen": 1000, "book": 5000, "bag": 20000}
cart = ["pen", "book", "pen", "bag", "pen"]
total = 0
counts = {}
for item in cart:
total += prices[item]
counts[item] = counts.get(item, 0) + 1
if total >= 25000:
total = int(total * 0.9)
print(total, counts["pen"])
① 25200 3 ② 28000 3 ③ 25200 2 ④ 25200 5 ⑤ Error