Menu
Coddy logo textTech

Recording Grades

Part of the Logic & Flow section of Coddy's R journey. Lesson 23 of 64.

challenge icon

Challenge

Easy

Add the GRADE command to gradebook(). Keep every command from the previous steps working exactly as before.

  • GRADE <name> <score>: if the student is not stored, reply no student <name>. Otherwise append the score to the student's grades and reply recorded <score> for <name>.

Scores are numbers such as 90 or 87.5; write them in the reply the way R prints the number.

The supplied code passes every input line to gradebook() as one command and prints each returned reply on its own line. A name is one lower-case word, and the input holds only the commands described so far.

Try it yourself

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))
      }
    }
  }
  replies
}

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(gradebook(input), sep = "\n")

All lessons in Logic & Flow

Practice on your own: Online R compiler