Menu
Coddy logo textTech

학급 보고서

Coddy R 여정의 논리와 흐름 섹션에 포함된 레슨. 64개 중 25번째.

challenge icon

챌린지

쉬움

REPORT 명령을 추가하세요. 이전 단계의 모든 명령이 이전과 정확히 동일하게 작동하도록 유지하세요.

  • REPORT: 저장된 각 학생에 대해 알파벳순으로 한 줄씩 응답하며, AVG의 응답과 같은 형식으로 표시합니다(ada: 88.8 또는 bo: no grades). 그런 다음 Class average: 줄을 추가하고, 모든 학생의 기록된 모든 성적의 평균을 소수점 한 자리로 표시하세요. 기록된 성적이 아무것도 없으면 no grades를 표시합니다.

하나의 REPORT 명령은 여러 응답을 생성하며, 각 응답은 한 줄에 하나씩 출력됩니다.

제공된 코드는 입력된 각 줄을 하나의 명령으로 gradebook()에 전달하고, 반환된 각 응답을 한 줄에 하나씩 출력합니다. 이름은 소문자로 된 한 단어이며, 입력에는 지금까지 설명한 명령만 포함됩니다.

직접 해보기

average_text <- function(scores) {
  if (length(scores) == 0) "no grades" else sprintf("%.1f", mean(scores))
}

gradebook <- function(commands) {
  grades <- list()
  replies <- c()
  for (cmd in commands) {
    parts <- strsplit(cmd, " ")[[1]]
    name <- parts[2]
    if (parts[1] == "ADD") {
      if (name %in% names(grades)) {
        replies <- c(replies, paste(name, "already exists"))
      } else {
        grades[[name]] <- numeric(0)
        replies <- c(replies, paste("added", name))
      }
    } else if (parts[1] == "GRADE") {
      if (!(name %in% names(grades))) {
        replies <- c(replies, paste("no student", name))
      } else {
        score <- as.numeric(parts[3])
        grades[[name]] <- c(grades[[name]], score)
        replies <- c(replies, paste("recorded", score, "for", name))
      }
    } else if (parts[1] == "AVG") {
      if (!(name %in% names(grades))) {
        replies <- c(replies, paste("no student", name))
      } else {
        replies <- c(replies, paste0(name, ": ", average_text(grades[[name]])))
      }
    }
  }
  replies
}

# 제공된 입력/출력 코드: 그대로 유지하세요
input <- suppressWarnings(readLines(file("stdin")))
cat(gradebook(input), sep = "\n")

논리와 흐름의 모든 레슨

직접 연습해 보세요: 온라인 R 컴파일러