Problem

Description

Given a year, return the century it is in. Note that the year should be interpreted via strict construction (as in the 19th century spans from the years 1901-2000) rather than popular perception (the 19th century spans from the years 1900-1999).

Test Cases

century(1601) # Returns 17
century(356) # Returns 4
century(89) # Returns 1 

Solution

My Solution

def century(year):
    return (year+99)//100

Other Solutions

from math import ceil

def century(year):
    return ceil(year / 100)

Learning Experiences

  • It's helpful to read more about the requirements of the task at hand. For instance, my solution utilises the double slash //, also known as floor division - this rounds the result down to the nearest whole number.
    • Given a year 1900, dividing (1900+99) by 100 would ordinarily result in a decimal number (19.99). However, using // instead rounds down to 19 which is correct according to the strict definition.
    • What is the purpose of adding 99? Well, for every case that is given, the only numbers that would require a substantial change are if the year was 2000 - in which case, the century is 20. For every other year in that same century (19xx), however, the century would be xx+1.
      • So, we add 99 to push the year up to the next century, so that we can then floor divide to obtain the first two digits - which, given how wack our year conventions are - is equal to the actual century number.
      • Why 99 and not 100? Centuries start at xx01 and end at (xx+1)00. Say that the year was 2000. Adding 99 makes it equal to 2099, whereas adding 100 makes it equal to 2100. We note that 2099/100 = 20, while 2100/100 = 21, the latter of which is incorrect.
  • Solution 1 shows not to be afraid to use external modules. ceil(foo) returns the foo rounded up to the nearest integer, if not already an integer. This works because our special cases (xx00) divided by 100 are still integers, so nothing happens to them.