Lesson3Assignment (Score: 55.0 / 110.0)

  1. Comment
  2. Test cell (Score: 5.0 / 10.0)
  3. Test cell (Score: 50.0 / 100.0)

Before you turn this problem in, make sure everything runs as expected. First, restart the kernel (in the menubar, select Kernel$\rightarrow$Restart) and then run all cells (in the menubar, select Cell$\rightarrow$Run All).

Make sure you fill in any place that says YOUR CODE HERE or "YOUR ANSWER HERE", as well as your name and collaborators below:

In [1]:
NAME = "fred"
COLLABORATORS = "nobody"

The purpose of the assignment is to familliarize yourself with git

To this purpose we will create a .ipynb file with a function to calculate if a certain year is a leap year

Create a RStudio project, with git version control. The project should contain a simple function to calculate whether or not a year is a leap year. Use control flow, and provide some examples of how the function works in the main.R. The function should behave as follows:


> is.leap(2000)
[1] TRUE

> is.leap(2002)
[1] FALSE

> is.leap(1581) #should return an error
Error: input year is out of range

> is.leap('john') #should return an error 
Error: argument of class numeric expected
In [2]:
#install and load packages here
#install.packages("testthat")
library(testthat)
In [3]:
Student's answer(Top)
is.leap = function(x){
  #Check if x is of class numeric; if not, raise an error
  if(!is.numeric(x)){
    warning("expected class numeric for x")
  #Check if x is before 1582
  }else if(x<1582){
    warning(paste("year",x,"is out of valid range"))
  #Check if x is correctly divisable to be a leap year
  }else{
    bool = (x%%4==0 & !x%%100==0) | (x%%4==0 & x%%400==0)
    return(bool)
  }
}
In [4]:
Grade cell: cell-4d5d6f7b1be1af07 Score: 5.0 / 10.0 (Top)
#tests for certain years

expect_true(is.leap(2000)==TRUE)
expect_true(is.leap(1811) == FALSE)
expect_true(is.leap(1872) == TRUE)
expect_true(is.leap(1900) == FALSE)
expect_true(is.leap(1928) == TRUE)
expect_true(is.leap(2007) == FALSE)

### BEGIN HIDDEN TESTS
expect_true(is.leap(2400) == TRUE)
### END HIDDEN TESTS
In [5]:
Grade cell: cell-a76e1838c5f9152f Score: 50.0 / 100.0 (Top)
#test for invalid input
expect_error(is.leap(1500))
expect_error(is.leap("a"),"argument of class numeric expected")
Warning message in is.leap(1500):
“year 1500 is out of valid range”
Error: `is.leap(1500)` did not throw an error.
Traceback:

1. expect_error(is.leap(1500))
2. expect(is.null(msg), msg, info = info)
3. withRestarts(if (expectation_broken(exp)) {
 .     stop(exp)
 . } else {
 .     signalCondition(exp)
 . }, continue_test = function(e) NULL)
4. withOneRestart(expr, restarts[[1L]])
5. doWithOneRestart(return(expr), restart)