Menu
Coddy logo textTech

Student Averages

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

challenge icon

Challenge

Easy

Add the AVG command. Keep every command from the previous steps working exactly as before.

  • AVG <name>: reply no student <name> for an unknown student, <name>: no grades for a student without grades, and otherwise <name>: followed by the mean of their grades with one decimal, such as ada: 88.8.

A helper function that turns a vector of scores into no grades or the formatted mean will be useful again in the next step.

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