HackerRank

Archives of practice questions & solutions

1. List Comprehensions

#You are given three integers X, Y and Z representing the dimensions of a cuboid along with an
# integer N. You have to print a list of all possible coordinates given by (i, j, k) on a 3D grid where the sum of i + j + k  is not
# equal to N. Here, 0 <= i <= X; 0 <= j <= Y; 0 <= k <= Z 

# Input Format : Four integers X, Y, Z and N each on four separate lines, respectively.

# Sample Input 1, 1,1,2 (all newlines)

# Sample Output
# [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]]

# Solution 1 - Loops. Read input from STDIN. Print output to STDOUT
if __name__ == '__main__':
    x = int(input())
    y = int(input())
    z = int(input())
    n = int(input())
    d = []
    for i in range(x+1):
        for j in range(y+1):
            for k in range(z+1):
                #return combo that do not sum to n
                if i + j + k != n:
                    a= [i,j,k]
                    d.append(a)
    print(d)
 ### solution 2 - List comprehension
x = [[i,j,k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if i+j+k!=n]  # sum only takes 2 arguments, cant use
print(x) # note: CANNOT USE RETURN, must assing variable before calling with return

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.

def is_leap(year):
    leap = False
    
    # Write your logic here
    if year % 4 ==0:
        if year%100 ==0 and year%400 !=0:
            leap = False
        elif year%100 ==0 and year%400 ==0:
            leap = True  
        else:
            leap = True    
    else:
        leap = False    
    return leap

year = int(input())
print(is_leap(year))

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

#EXAMPLE TUTORIAL - occurrence of word 'good' from index 0 to 25 (CANT WORK FOR THIS QN)   
str1 = "This dress looks good; you have good taste in clothes."
substr = "good"
count2 = str1.count(substr,0,25)
print(count2)

## Question Answer
def count_substring(string, sub_string):
    string_l = len(string)
    substring_l = len(sub_string)
    count = 0
    for i in range(0, string_l -1):
        if string[i:i+substring_l] == sub_string:
            count +=1
    return count

if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()
    
    count = count_substring(string, sub_string)
    print(count)

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!)

n = int(input())

nums = map(int, input().split())   # processed array [2,3,4] 
print(sorted(list(set(nums)))[-2])

Explanation

So we can take this line:

nums = map(int, input().split())

And break it down into a few subparts:

nums_in = input()
nums_split = nums_in.split()
nums = map(int, nums_split)

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_in = "1 5 73 29"

nums_split will then be the list of numbers split into a string for each number:

nums_split = ["1", "5", "73", "29"]

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:

nums = [1, 5, 73, 29]

The map function in Python 2 always returns a list, so in Python 3, we need to add one more step:

nums = list(map(int, nums_split))

Or, use one of my favorite Python structures in both, the list comprehension:

nums = [int(n) for n in nums_split]

Last updated