HackerRank Python Solution - Errors and Exception

Errors detected during execution are called exceptions.

Examples:

ZeroDivisionError:

This error is raised when the second argument of a division or modulo operation is zero.
 
>>> a = '1'
>>> b = '0'
>>> print int(a) / int(b)
>>> ZeroDivisionError: integer division or modulo by zero

HackerRank Python Solution - Date and Time - Time Delta

  • When users post an update on social media, such as a URL, image, status update, etc., other users in their network are able to view this new post on their news feed. Users can also see exactly when the post was published, i.e, how many hours, minutes, or seconds ago.
  • Since sometimes posts are published and viewed in different time zones, this can be confusing. You are given two timestamps of one such post that a user can see on his newsfeed in the following format:
  • Day dd Mon yyyy hh:mm:ss +xxxx
  • Here +xxxx represents the time zone. Your task is to print the absolute difference (in seconds) between them.

HackerRank Python Solution - Date and Time - Calendar Module

  • The calendar module allows you to output calendars and provides additional useful functions for them.
  • class calendar.TextCalendar([firstweekday])
  • This class can be used to generate plain text calendars.
Sample Code:

HackerRank Python Solution - Collections Topic - Counter()

A counter is a container that stores elements as dictionary keys and their counts are stored as dictionary values.

Sample Code:

>>> from collections import Counter
>>> 
>>> myList = [1,1,2,3,4,5,3,2,3,4,2,1,2,3]
>>> print Counter(myList)
Counter({2: 4, 3: 4, 1: 3, 4: 2, 5: 1})
>>>
>>> print Counter(myList).items()
[(1, 3), (2, 4), (3, 4), (4, 2), (5, 1)]
>>> 
>>> print Counter(myList).keys()
[1, 2, 3, 4, 5]
>>> 
>>> print Counter(myList).values()
[3, 4, 4, 2, 1]

HackerRank Python Solution - Collections Topic - deque()

  • A deque is a double-ended queue. It can be used to add or remove elements from both ends.
  • Deques support thread-safe, memory-efficient appends, and pops from either side of the deque with approximately the same O(1) performance in either direction.

HackerRank Python Solution - Collections Topic - OrderedDict

An OrderedDict is a dictionary that remembers the order of the keys that were inserted first. If a new entry overwrites an existing entry, the original insertion position is left unchanged.

Example Code:


>>> from collections import OrderedDict
>>> 
>>> ordinary_dictionary = {}
>>> ordinary_dictionary['a'] = 1
>>> ordinary_dictionary['b'] = 2
>>> ordinary_dictionary['c'] = 3
>>> ordinary_dictionary['d'] = 4
>>> ordinary_dictionary['e'] = 5
>>> 
>>> print ordinary_dictionary
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
>>> 
>>> ordered_dictionary = OrderedDict()
>>> ordered_dictionary['a'] = 1
>>> ordered_dictionary['b'] = 2
>>> ordered_dictionary['c'] = 3
>>> ordered_dictionary['d'] = 4
>>> ordered_dictionary['e'] = 5
>>> 
>>> print ordered_dictionary
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)])

HackerRank Python Solution - Collections Topic - namedtuple()

  • Basically, namedtuples are easy to create, lightweight object types.
  • They turn tuples into convenient containers for simple tasks.
  • With namedtuples, you don’t have to use integer indices for accessing members of a tuple.
Example:

Code 01:

>>> from collections import namedtuple
>>> Point = namedtuple('Point','x,y')
>>> pt1 = Point(1,2)
>>> pt2 = Point(3,4)
>>> dot_product = ( pt1.x * pt2.x ) +( pt1.y * pt2.y )
>>> print dot_product
11

HackerRank Python Solution - Collections Topic - DefaultDict

The defaultdict tool is a container in the collections class of Python. It's similar to the usual dictionary (dict) container, but the only difference is that a defaultdict will have a default value if that key has not been set yet. If you didn't use a defaultdict you'd have to check to see if that key exists, and if it doesn't, set it to what you want.

For example:
 
from collections import defaultdict
d = defaultdict(list)
d['python'].append("awesome")
d['something-else'].append("not relevant")
d['python'].append("language")
for i in d.items():
    print i

HackerRank Python Solution - Itertools Topic - Maximize it!

  • You are given a function f(X) = X2. You are also given K lists. The ith list consists of Nelements.
  • You have to pick one element from each list so that the value from the equation below is maximized:
  • S = (f(X1) + f(X2) +....+ f(Xk)) % M
  • Xi denotes the element picked from the ith list. Find the maximized value Smax obtained.
  • % denotes the modulo operator.
  • Note that you need to take exactly one element from each list, not necessarily the largest element. You add the squares of the chosen elements and perform the modulo operation. The maximum value that you can obtain, will be the answer to the problem.

HackerRank Python Solution - Itertools Topic - iterables and iterators

  • The itertools module standardizes a core set of fast, memory-efficient tools that are useful by themselves or in combination. Together, they form an iterator algebra making it possible to construct specialized tools succinctly and efficiently in pure Python.
  • You are given a list of N lowercase English letters. For a given integer K, you can select any K indices (assume 1-based indexing) with a uniform probability from the list.
  • Find the probability that at least one of the K indices selected will contain the letter: 'a'.

HackerRank Python Solution - Itertools Topic - Compress the String!

  • In this task, we would like for you to appreciate the usefulness of the groupby() function of itertools.
  • You are given a string S. Suppose a character 'c' occurs consecutively X times in the string. Replace these consecutive occurrences of the character 'c' with (X,c) in the string.
  • For a better understanding of the problem, check the explanation.
Input Format:

A single line of input consisting of the string S.

You might also like

Deploy your Django web app to Azure Web App using App Service - F1 free plan

In this post, we will look at how we can deploy our Django app using the Microsoft Azure app service - a free plan. You need an Azure accoun...