HackerRank
Archives of practice questions & solutions
1. List Comprehensions
2. Leap Year (if else)
An extra day is added to the calendar almost every four years as February 29, and the day is called a leap day. It corrects the calendar for the fact that our planet takes approximately 365.25 days to orbit the sun. A leap year contains a leap day.
In the Gregorian calendar, three conditions are used to identify leap years:
The year can be evenly divided by 4, is a leap year, unless:
The year can be evenly divided by 100, it is NOT a leap year, unless:
The year is also evenly divisible by 400. Then it is a leap year.
This means that in the Gregorian calendar, the years 2000 and 2400 are leap years, while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years.
3. Substring Counting
In this challenge, the user enters a string and a substring. You have to print the number of times that the substring occurs in the given string. String traversal will take place from left to right, not from right to left.
Trick: input ABCDCDC will give 2 as output! So gotta iterate thru individual characters
4. Find first runner up (second highest)
use set to remove duplicates set(array)
make the set a list (as sorted can only work on iterable = list)
use sorted to arrange
Count from -2 index (second biggest!)
Explanation
So we can take this line:
And break it down into a few subparts:
In order, nums_in
will be the list of numbers read in as a string. For the input string "1 5 73 29"
, it will be:
nums_split
will then be the list of numbers split into a string for each number:
Now, the map
function will call a function (int
in this case) on each item in a list ("1", "5", "73", "29"
in this case), and create a new list with the values that function returns. So, for this example:
The map
function in Python 2 always returns a list, so in Python 3, we need to add one more step:
Or, use one of my favorite Python structures in both, the list comprehension:
Last updated