Top Student
Part of the Logic & Flow section of Coddy's R journey. Lesson 26 of 64.
Challenge
MediumAdd the TOP command. Keep every command from the previous steps working exactly as before.
TOP: replyTop:followed by the student with the highest mean and that mean with one decimal in brackets, such asTop: ada (92.0). Students without grades are skipped. When means tie, pick the student whose name comes first alphabetically. When no student has grades, replyTop: none.
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
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]])))
}
} else if (parts[1] == "REPORT") {
for (student in sort(names(grades))) {
replies <- c(replies, paste0(student, ": ", average_text(grades[[student]])))
}
replies <- c(replies, paste("Class average:", average_text(unlist(grades))))
}
}
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
1Strings In Depth
Substrings with substr()Formatting with sprintf()Splitting and JoiningSearching StringsReplacing TextRecap - Username Builder4Matrices
Creating MatricesIndexing MatricesRow and Column SummariesMatrix ArithmeticRecap - Seating Chart2Key-Value Lookups
Named Vector LookupsChecking KeysAdding and Removing KeysLooping Over NamesRecap - Stock Desk3Sets and Counting
Unique ValuesSet OperationsMembership TestsCounting with table()Recap - Event Guests6Functions as Values
Anonymous FunctionsPassing FunctionsReturning FunctionsClosures with StateRecap - Discount Rules9Data Frames
Creating Data FramesColumns and RowsFiltering RowsAdding and SortingRecap - Sales Report12Project - Expense Tracker
Recording ExpensesTotal SpendingPractice on your own: Online R compiler