파이썬 서술형 — SET 20¶
이름: ____________ 점수: _____ / 100
출력형은 실행 결과와 그렇게 되는 이유를 함께 서술하세요. 작성형은 실행 가능한 코드로 답하세요. (범위: 함수·클래스·모듈/패키지·딕셔너리·리스트·튜플·set 심화)
[Ⅰ. 출력 예측 + 이유 서술] (각 10점)¶
1.¶
def memo_fib(n, cache={}):
if n in cache:
return cache[n]
if n <= 1:
result = n
else:
result = memo_fib(n - 1, cache) + memo_fib(n - 2, cache)
cache[n] = result
return result
print(memo_fib(5), len(memo_fib.__defaults__[0]))
출력: ________________
이유:
2.¶
nums = [1, 2, 3, 4, 5, 6, 7, 8]
result = {n: ("even" if n % 2 == 0 else "odd") for n in nums if n > 3}
print(result)
출력: ________________
이유:
3.¶
a = [[1, 2], [3, 4]]
b = a[:]
b.append([5, 6])
b[0][0] = 99
print(a, b)
출력: ________________
이유:
4.¶
import random
random.seed(2)
sample = random.sample(range(1, 50), 6)
print(len(sample), len(set(sample)) == len(sample))
출력: ________________
이유:
[Ⅱ. 코드 작성] (각 15점)¶
5. (클래스) add(item, qty)로 재고를 늘리고, remove(item, qty)로 줄이되 0 미만으로 내려가지 않게 하는 Inventory 클래스를 작성하세요. get(item)은 현재 수량을(없으면 0을) 반환합니다.¶
inv = Inventory()
inv.add("apple", 5)
inv.remove("apple", 3)
print(inv.get("apple"), inv.get("banana"))
→ 2 0
6. (튜플) 숫자 리스트를 짝수 리스트와 홀수 리스트로 나누어 (짝수리스트, 홀수리스트) 튜플로 반환하는 함수 group_by_parity(nums)를 작성하세요.¶
group_by_parity([1, 2, 3, 4, 5]) → ([2, 4], [1, 3, 5])
7. (set) 작은 집합 small이 list_of_sets에 있는 집합들 중 하나의 부분집합이면 True를 반환하는 함수 is_subset_of_any(small, list_of_sets)를 작성하세요.¶
is_subset_of_any({1, 2}, [{1, 2, 3}, {4, 5}]) → True
[Ⅲ. 오류 찾기·수정] (15점)¶
8.¶
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
def to_fahrenheit(self):
return self.celsius * 9 / 5 + 32
def __str__(self):
return f"{self.celsius}C = {self.to_fahrenheit}F"
t = Temperature(100)
print(t)
이 코드를 실행하면 어떤 문제가 발생하는지 설명하고, 올바르게 고친 코드를 작성하세요.