HackerRank Python Solution - Classes - Dealing with Complex Numbers

  • For this challenge, you are given two complex numbers, and you have to print the result of their addition, subtraction, multiplication, division, and modulus operations.
  • The real and imaginary precision parts should be correct up to two decimal places.
Input Format:

One line of input: The real and imaginary part of a number separated by a space.

Python - File Handling

In real-world application development, the logic that we implement uses some data and those data may come from different sources like databases, files, or API. As a python developer, we should have good knowledge of handling these different sources. In this tutorial, we will see how we can handle files and perform some operations using python in-built functions.

Basically, a file is a location to store information in non-volatile memory (Hard Disk). And, it is characterized by its name and extension.

When we want to perform some operation(Read/Write/Update) in a file, we will open it first. Then we perform our task and finally, we will close it to save the changes and deallocate the resources tied with the file.

Similarly, in python, File operation takes place in the following order:

  1. Open a file
  2. Perform operation (Read/Write/Update)
  3. Close the file

Python - Exception Handling

Errors are unavoidable. As a developer, we always have to encounter multiple errors in the initial phase of development. And at the end of the development, the business logic/application which we developed should not misbehave or terminate due to some unexpected events during execution.

In General, Errors in python can be of two types

  • Syntax Errors/Compile Time Error - Syntax mistakes which result in termination of the program.
#syntax error example
a = 5
if(a)
print("Value present")

#result
File "main.py", line 2
    if(a)
        ^
SyntaxError: invalid syntax

HackerRank Python Solution - Errors and Exception - Incorrect Regex

  • You are given a string S.
  • Your task is to find out whether S is a valid regex or not.
Input Format:
  • The first line contains integer T, the number of test cases.
  • The next T lines contain the string S.

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

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...