Python leap year..

Charles Butler Jr
3 min readJul 30, 2021

--

Continuing my python HackerRank challenges we’re met with a new prompt. Given a year (test input & custom input), our function is to return whether it is a leap year or not due to custom constraints/ if statements within the block of code. The return value will be a boolean (True / False) depending on the constraints to be mentioned.

Here we see a list of constraints for what defines a leap year:

  • Can be divisible by 4
  • Unless it can be evenly divided by 100 (which mean’s it is not)
  • & Unless it can be divided by 400 (which would make it a leap year)

My first attempt gave me 5/6 test cases passing, but utilized simple logic. I had the ‘if statement’ coinditioned for the first constraint showing that the number is / is not divisible by 4 otherwise show false.

Next I added the other logic how I best thought it fit. Unfortunately this is where things became tricky.

This is best explained as an if statement within an if statement. Where the divisible by 100 & elif divisible by 400 statements are within the orignal logic of divisibility by 4. Unfortunatley my logic was flawed and I failed 2/6 test cases.

Refactoring my code a few more times led to the same result, until i realized that the answer was buried in the way the problem was written. It flowed as if the conditions were all one line.

I could sum it up like this:

‘if year is divisible by 4 AND (x is true OR y is true)”

which brought me to a single line of code in my functions block:

Here you can see that the main condiditonal (like my previous parent if statement) has children conditionals/ where divisible by 400 or divisible by 100 stand out as or statements. From here Clicking submit had all tests passing.

--

--

Charles Butler Jr
Charles Butler Jr

Written by Charles Butler Jr

Pre-Med student turned software engineer. Hoping to make code make sense & make sense out of all my code.