← 목록

정보처리기사 실기 2025년 1회

Q.142025년1회8과목 · Python배점 5점
아래 코드의 출력값을 작성하시오.
class Node:
    def __init__(self, value):
        self.value = value
        self.children = []

def tree(li):
    nodes = [Node(i) for i in li]
    for i in range(1, len(li)):
        nodes[(i - 1) // 2].children.append(nodes[i])
    return nodes[0]

def calc(node, level=0):
    if node is None:
        return 0
    return (node.value if level % 2 == 1 else 0) \
         + sum(calc(n, level + 1) for n in node.children)

li = [3, 5, 8, 12, 15, 18, 21]
root = tree(li)
print(calc(root))
댓글2개

나만의 풀이, 암기법을 나눠 보세요. 정답이 포함될 수 있어요.

고요한 무당벌레앞뒤 밑줄 두 개짜리 이름은 특별해요 __이름__처럼 앞뒤에 밑줄 두 개가 붙은 함수는 파이썬이 특정 상황에 자동으로 부르는 예약된 이름이에요. 매직 메서드라고 불러요. 이름 자동 실행되는 때 __init__ 객체를 만들 때 __str__ print()로 출력할 때 __len__ len()을 쓸 때10월 20일
고요한 무당벌레[ ... ]는 리스트 {키: 값, ...}는 딕셔너리10월 20일
해설
왼쪽에서 보기를 고르고 정답 확인을 누르면
여기에 정답과 해설이 표시됩니다.