콘텐츠로 이동

파이썬 객관식 심화 — 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 FalseTrue False TrueFalse False TrueTrue False FalseError

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 drawwin win drawlose win drawwin lose loseError

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 9232111 9232111 2770 9232112 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)

23415

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 155 58 155 95 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)))

152072036Error

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 45 9 36 9 36 8 3Error