파이썬 객관식 심화 — SET 14 (긴 코드)¶
이름: ____________ 점수: _____ / 100 난이도: ★★★★★
다소 긴 프로그램입니다. 차분히 끝까지 추적하여 실행 결과를 고르세요. (문항당 10점, 범위: 1~8장 종합)
1. (투 포인터·회문)¶
def is_palindrome(s):
i = 0
j = len(s) - 1
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
print(is_palindrome("level"), is_palindrome("hello"), is_palindrome("noon"))
① True True False ② True False True ③ False False True ④ True False False ⑤ Error
2. (딕셔너리 규칙)¶
def judge(a, b):
if a == b:
return "draw"
wins = {"rock": "scissors", "scissors": "paper", "paper": "rock"}
if wins[a] == b:
return "win"
return "lose"
print(judge("rock", "scissors"), judge("rock", "paper"), judge("paper", "paper"))
① win lose draw ② win win draw ③ lose win draw ④ win lose lose ⑤ Error
3. (while·최댓값 추적)¶
n = 27
steps = 0
peak = n
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
if n > peak:
peak = n
steps += 1
print(steps, peak)
① 27 9232 ② 111 9232 ③ 111 27 ④ 70 9232 ⑤ 112 9232
4. (중첩 for·쌍 세기)¶
nums = [1, 5, 7, -1, 5]
target = 6
count = 0
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
count += 1
print(count)
① 2 ② 3 ③ 4 ④ 1 ⑤ 5
5. (재귀·호출 횟수)¶
calls = 0
def fib(n):
global calls
calls += 1
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
result = fib(5)
print(result, calls)
① 5 15 ② 5 5 ③ 8 15 ④ 5 9 ⑤ 5 11
6. (클래스·큐)¶
class Queue:
def __init__(self):
self.items = []
def enqueue(self, x):
self.items.append(x)
def dequeue(self):
if self.items:
return self.items.pop(0)
return None
q = Queue()
q.enqueue(10)
q.enqueue(20)
q.enqueue(30)
first = q.dequeue()
q.enqueue(40)
second = q.dequeue()
print(first, second, q.items)
① 10 20 [40] ② 10 20 [30, 40] ③ 30 40 [10, 20] ④ 10 40 [30] ⑤ Error
7. (예외·검증)¶
def validate(inputs):
valid = []
invalid = 0
for x in inputs:
try:
num = int(x)
if num < 0:
raise ValueError
valid.append(num)
except ValueError:
invalid += 1
return valid, invalid
print(validate(["5", "-3", "abc", "10", "-1", "7"]))
① ([5, 10, 7], 3) ② ([5, 10, 7], 2) ③ ([5, -3, 10, -1, 7], 1) ④ ([5, 10, 7], 1) ⑤ Error
8. (모듈·조합)¶
import math
print(math.factorial(6) // (math.factorial(3) * math.factorial(3)))
① 15 ② 20 ③ 720 ④ 36 ⑤ Error
9. (리스트·누적 최댓값)¶
nums = [4, 2, 7, 1, 9, 3, 8]
result = []
current_max = nums[0]
for n in nums:
if n > current_max:
current_max = n
result.append(current_max)
print(result)
① [9, 9, 9, 9, 9, 9, 9] ② [4, 4, 7, 7, 9, 9, 9] ③ [4, 2, 7, 1, 9, 3, 8] ④ [4, 4, 7, 7, 9, 9, 8] ⑤ Error
10. (종합·길이별 집계)¶
text = "the quick brown fox the lazy dog the end"
words = text.split()
length_count = {}
for w in words:
L = len(w)
length_count[L] = length_count.get(L, 0) + 1
print(length_count[3], len(words), len(length_count))
① 6 9 4 ② 5 9 3 ③ 6 9 3 ④ 6 8 3 ⑤ Error