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.

HackerRank Python Solution - Itertools Topic - itertools.combinations_with_replacement()

itertools.combinations_with_replacement(iterable, r):
  • This tool returns r length subsequences of elements from the input iterable allowing individual elements to be repeated more than once.
  • Combinations are emitted in lexicographic sorted order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.
Sample Code:

>>> from itertools import combinations_with_replacement
>>> 
>>> print list(combinations_with_replacement('12345',2))
[('1', '1'), ('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('2', '2'), ('2', '3'), ('2', '4'), ('2', '5'), ('3', '3'), ('3', '4'), ('3', '5'), ('4', '4'), ('4', '5'), ('5', '5')]
>>> 
>>> A = [1,1,3,3,3]
>>> print list(combinations(A,2))
[(1, 1), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (1, 3), (3, 3), (3, 3), (3, 3)]

HackerRank Python Solution - Itertools Topic - itertools.combinations()

itertools.combinations(iterable, r):
  • This tool returns the length subsequences of elements from the input iterable.
  • Combinations are emitted in lexicographic sorted order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.
Sample Code:

>>> from itertools import combinations
>>> 
>>> print list(combinations('12345',2))
[('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('2', '3'), ('2', '4'), ('2', '5'), ('3', '4'), ('3', '5'), ('4', '5')]
>>> 
>>> A = [1,1,3,3,3]
>>> print list(combinations(A,4))
[(1, 1, 3, 3), (1, 1, 3, 3), (1, 1, 3, 3), (1, 3, 3, 3), (1, 3, 3, 3)]

HackerRank Python Solution - Itertools Topic - itertools.permutations()

itertools.permutations(iterable[, r]):
  • This tool returns successive length permutations of elements in an iterable.
  • If r is not specified or is None, then r defaults to the length of the iterable, and all possible full-length permutations are generated.
  • Permutations are printed in a lexicographic sorted order. So, if the input iterable is sorted, the permutation tuples will be produced in sorted order.
Sample Code:
>>> from itertools import permutations
>>> print permutations(['1','2','3'])
<itertools.permutations object at 0x02A45210>
>>> 
>>> print list(permutations(['1','2','3']))
[('1', '2', '3'), ('1', '3', '2'), ('2', '1', '3'), ('2', '3', '1'), ('3', '1', '2'), ('3', '2', '1')]
>>> 
>>> print list(permutations(['1','2','3'],2))
[('1', '2'), ('1', '3'), ('2', '1'), ('2', '3'), ('3', '1'), ('3', '2')]
>>>
>>> print list(permutations('abc',3))
[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]

HackerRank Python Solution - Itertools Topic - itertools.product()

itertools.product():
  • This tool computes the cartesian product of input iterables.
  • It is equivalent to nested for-loops.
  • For example, product(A, B) returns the same as ((x,y) for x in A for y in B).
Sample Code:

>>> from itertools import product
>>>
>>> print list(product([1,2,3],repeat = 2))
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
>>>
>>> print list(product([1,2,3],[3,4]))
[(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)]
>>>
>>> A = [[1,2,3],[3,4,5]]
>>> print list(product(*A))
[(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 3), (3, 4), (3, 5)]
>>>
>>> B = [[1,2,3],[3,4,5],[7,8]]
>>> print list(product(*B))
[(1, 3, 7), (1, 3, 8), (1, 4, 7), (1, 4, 8), (1, 5, 7), (1, 5, 8), (2, 3, 7), (2, 3, 8), (2, 4, 7), (2, 4, 8), (2, 5, 7), (2, 5, 8), (3, 3, 7), (3, 3, 8), (3, 4, 7), (3, 4, 8), (3, 5, 7), (3, 5, 8)]

HackerRank Python Solution - Math Topic - Triangle Quest

  • You are given a positive integer N. Print a numerical triangle of height N-1 like the one below:
1
22
333
4444
55555
......
  • Can you do it using only arithmetic operations, a single for loop, and print statement?
  • Use no more than two lines. The first line (the for statement) is already written for you. You have to complete the print statement.
  • Note: Using anything related to strings will give a score of 0.

HackerRank Python Solution - Math Topic - Integer Come In All Sizes

  • Integers in Python can be as big as the bytes in your machine's memory. There is no limit in size as there is: 231-1 (c++ int) or 263-1 (C++ long long int).
  • As we know, the result of ab grows really fast with increasing b.
  • Let's do some calculations on very large integers.

HackerRank Python Solution - Math Topic - Power - Mod Power

  • So far, we have only heard of Python's powers. Now, we will witness them!
  • Powers or exponents in Python can be calculated using the built-in power function. Call the power function ab as shown below:
>>> pow(a,b) 
or
 
>>> a**b
It's also possible to calculate ab mod m.
 
>>> pow(a,b,m)  

HackerRank Python Solution - Math Topic - Mod Divmod

One of the built-in functions of Python is divmod, which takes two arguments a and b, and returns a tuple containing the quotient of a/b first and then the remainder a.

For example:
 
>>> print divmod(177,10)
(17, 7)
Here, the integer division is 177/10 => 17 and the modulo operator is 177%10 => 7.

HackerRank Python Solution - Math Topic - Triangle Quest 2

  • You are given a positive integer N.
  • Your task is to print a palindromic triangle of size N.
  • For example, a palindromic triangle of size 5 is:
1
121
12321
1234321
123454321
  • You can't take more than two lines. The first line (a for-statement) is already written for you.
  • You have to complete the code using exactly one print statement. 

HackerRank Python Solution - Math Topic - Find Angle MBC

  • ABC is a right triangle, 90˙ at B. Therefore ∡ABC = 90˙
HackerRank Python Solution - Math Topic - Find Angle MBC
  • Point M is the midpoint of hypotenuse AC.
  • You are given the lengths AB and BC.
  • Your task is to find ∡MBC (angle Ó¨˙, as shown in the figure) in degrees.
Input Format:
  • The first line contains the length of side AB.
  • The second line contains the length of side BC.

HackerRank Python Solution - Math Topic - Polar Coordinates

  • Polar coordinates are an alternative way of representing Cartesian coordinates or Complex Numbers.
  • A complex number z = x + yj,  is completely determined by its real part x and imaginary part y. Here, j is the imaginary unit. 
  • A polar coordinate (r,φ) is completely determined by modulus r and phase angle φ.
  • If we convert complex number z to its polar coordinate, we find:
    • r: Distance from to origin, i.e., √ (x^2 + y^2)
    • φ: Counterclockwise angle measured from the positive x-axis to the line segment that joins z to the origin. 
  •  Python's cmath module provides access to the mathematical functions for complex numbers.

HackerRank Python Solution - Numpy Topic - Linear Algebra

The NumPy module also comes with a number of built-in routines for linear algebra calculations. These can be found in the sub-module linalg.

linalg.det:

The linalg.det tool computes the determinant of an array.

print numpy.linalg.det([[1 , 2], [2, 1]])       #Output : -3.0
linalg.eig:

The linalg.eig computes the eigenvalues and right eigenvectors of a square array.

HackerRank Python Solution - Numpy Topic - Polynomials

Poly:

The poly tool returns the coefficients of a polynomial with the given sequence of roots.

print numpy.poly([-1, 1, 1, 10])        #Output : [  1 -11   9  11 -10]
Roots:

The roots tool returns the roots of a polynomial with the given coefficients.

HackerRank Python Solution - Numpy Topic - Inner and Outer

Inner:

The inner tool returns the inner product of two arrays.

import numpy

A = numpy.array([0, 1])
B = numpy.array([3, 4])

print numpy.inner(A, B)     #Output : 4

HackerRank Python Solution - Numpy Topic - Dot and Cross

Dot:

The dot tool returns the dot product of two arrays.

import numpy

A = numpy.array([ 1, 2 ])
B = numpy.array([ 3, 4 ])

print numpy.dot(A, B)       #Output : 11

HackerRank Python Solution - Numpy Topic - Mean, Var, and Std

Mean:

The mean tool computes the arithmetic mean along the specified axis.

import numpy

my_array = numpy.array([ [1, 2], [3, 4] ])

print numpy.mean(my_array, axis = 0)        #Output : [ 2.  3.]
print numpy.mean(my_array, axis = 1)        #Output : [ 1.5  3.5]
print numpy.mean(my_array, axis = None)     #Output : 2.5
print numpy.mean(my_array)                  #Output : 2.5
By default, the axis is None. Therefore, it computes the mean of the flattened array.

HackerRank Python Solution - Numpy Topic - Min and Max

Min:

The tool min returns the minimum value along a given axis.

import numpy

my_array = numpy.array([[2, 5], 
                        [3, 7],
                        [1, 3],
                        [4, 0]])

print numpy.min(my_array, axis = 0)         #Output : [1 0]
print numpy.min(my_array, axis = 1)         #Output : [2 3 1 0]
print numpy.min(my_array, axis = None)      #Output : 0
print numpy.min(my_array)                   #Output : 0
By default, the axis value is None. Therefore, it finds the minimum over all the dimensions of the input array.

HackerRank Python Solution - Numpy Topic - Sum and Prod

Sum:

The sum tool returns the sum of array elements over a given axis.

import numpy

my_array = numpy.array([ [1, 2], [3, 4] ])

print numpy.sum(my_array, axis = 0)         #Output : [4 6]
print numpy.sum(my_array, axis = 1)         #Output : [3 7]
print numpy.sum(my_array, axis = None)      #Output : 10
print numpy.sum(my_array)                   #Output : 10
By default, the axis value is None. Therefore, it performs a sum over all the dimensions of the input array. 

HackerRank Python Solution - Numpy Topic - Floor, Ceil and Rint

Floor:

The tool floor returns the floor of the input element-wise. The floor of x is the largest integer i where i<=x.

import numpy

my_array = numpy.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])
print numpy.floor(my_array)         #[ 1.  2.  3.  4.  5.  6.  7.  8.  9.]
Ceil:

The tool ceil returns the ceiling of the input element-wise. The ceiling of x is the smallest integer i where i >= x.

HackerRank Python Solution - Numpy Topic - Shape and Reshape

Shape:

The shape tool gives a tuple of array dimensions and can be used to change the dimensions of an array. 

(a). Using shape to get array dimensions

import numpy

my__1D_array = numpy.array([1, 2, 3, 4, 5])
print my_1D_array.shape     #(5,) -> 1 row and 5 columns

my__2D_array = numpy.array([[1, 2],[3, 4],[6,5]])
print my_2D_array.shape     #(3, 2) -> 3 rows and 2 columns 

HackerRank Python Solution - Numpy Topic - Array Mathematics

Basic mathematical functions operate elementwise on arrays. They are available both as operator overloads and as functions in the NumPy module.

import numpy

a = numpy.array([1,2,3,4], float)
b = numpy.array([5,6,7,8], float)

print a + b                     #[  6.   8.  10.  12.]
print numpy.add(a, b)           #[  6.   8.  10.  12.]

print a - b                     #[-4. -4. -4. -4.]
print numpy.subtract(a, b)      #[-4. -4. -4. -4.]

print a * b                     #[  5.  12.  21.  32.]
print numpy.multiply(a, b)      #[  5.  12.  21.  32.]

print a / b                     #[ 0.2         0.33333333  0.42857143  0.5       ]
print numpy.divide(a, b)        #[ 0.2         0.33333333  0.42857143  0.5       ]

print a % b                     #[ 1.  2.  3.  4.]
print numpy.mod(a, b)           #[ 1.  2.  3.  4.]

print a**b                      #[  1.00000000e+00   6.40000000e+01   2.18700000e+03   6.55360000e+04]
print numpy.power(a, b)         #[  1.00000000e+00   6.40000000e+01   2.18700000e+03   6.55360000e+04]

HackerRank Python Solution - Numpy Topic - Eye and Identity

Identity:

The identity tool returns an identity array. An identity array is a square matrix with all the main diagonal elements as 1 and the rest as 0. The default type of element is float.

import numpy
print numpy.identity(3) #3 is for  dimension 3 X 3

#Output
[[ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  0.  1.]]

HackerRank Python Solution - Numpy Topic - Zeros and Ones

Zeros:

The zeros tool returns a new array with a given shape and type filled with 0's.

import numpy

print numpy.zeros((1,2))                    #Default type is float
#Output : [[ 0.  0.]] 

print numpy.zeros((1,2), dtype = numpy.int) #Type changes to int
#Output : [[0 0]]

HackerRank Python Solution - Numpy Topic - Concatenate

Concatenate:

Two or more arrays can be concatenated together using the concatenate function with a tuple of the arrays to be joined:

import numpy

array_1 = numpy.array([1,2,3])
array_2 = numpy.array([4,5,6])
array_3 = numpy.array([7,8,9])

print numpy.concatenate((array_1, array_2, array_3))    

#Output
[1 2 3 4 5 6 7 8 9]

HackerRank Python Solution - Numpy Topic - Transpose and Flatten

Question 2 - Transpose and Flatten

Task

You are given an NxM integer array matrix with space-separated elements (N= rows and M= columns).
The question is to print the transpose and flatten the results.

Input Format

The first line contains the space-separated values of N and M.
The next N lines contain the space-separated elements of M columns.

HackerRank Python Solution - Numpy Topic - Arrays

Question1 - Arrays:

Task

You are given a space-separated list of numbers.
Your task is to print a reversed NumPy array with the element type float.

Input Format

A single line of input containing space-separated numbers.

Library List in AS400

Library List: 
Library List in AS400
  • A library list is a list of libraries maintained for each user session with the libraries arranged in decreasing order of priority.
  • Whenever an object is referenced in command without a library, then the system starts checking for the object in all the libraries in the library list.
  • If the object is found in the first library, then the system picks that object from that first library.
  • If the object is not found in any library in the library list then the system will throw an error.

How to Check If Hard Drive is SSD or HDD in Windows 10

Ever wondered how to check the type of Hard Drive installed on your computer. Here, we will see two different methods to check if Hard Drive is SSD (Solid State Drive) or HDD (Hard Disk Drive) in windows 10.

Method 1: Using Disk Defragmenter/Windows Drive Optimizer

  • Type 'Defrag' in the search bar of the start menu and select "Defragment and Optimize Drives - App".

HTML - Horizontal Line

Horizontal line:

  • A horizontal line in HTML is defined by using the tag <hr>. Here hr stands for a horizontal rule.
  • <hr> tag is used to insert a thematic break in an HTML page or to separate the contents on the page.
  • <hr> tag is an empty tag that doesn't have a closing/end tag.
  • It comprises of the below attributes

HTML - Images

  • HTML <img> tag is used to display  images in the web page.
  • The images are just linked, not inserted into the web page. The <img> creates a holding space for the image.
  • The <img> tag is an empty tag that doesn't have a closing tag. It contains only attributes.
  • The required attributes of the <img> tag are
    • src - Specifies the path of the image
    • alt - Specifies alternate text for the image
      <img src="url" alt="alternate-text">

HTML - Text Formatting

Text Formatting:

  • In HTML, we have various elements to format text with special meaning. Such various elements are
    • Font <font>
    • Font Styles
    • Font Effects
Font <font> Element:
  • It defines the appearance of text on the web page by changing the font, size, and color.

HTML - Lists

Lists:

  • HTML List is used for grouping a set of related items in a list on the webpage.
  • In HTML, we have three different methods of specifying list information.
    • Ordered lists <ol>
    • Unordered lists <ul>
    • Description lists <dl>

HTML - Blockquotes

Blockquotes:

  • The Blockquote <blockquote> tag defines the content from another source with indentation.
  • The Blockquote will have a line break before and after the content by default.
  • URL of the source content can be given using the cite attribute and text representation can be given using the <cite> element.
  • For Short or Inline quotes, we can use the <q> tag.

HTML - Paragraphs

Paragraphs:

  • In HTML, the default paragraph defined in source code is ignored and it will be presented in a single block.
  • To add a manual paragraph, we can use the <p> tag with align attribute left, right, justify.


     <p align="center">paragraph goes here</p>

  • The paragraph defined using <p> will always start on a new line and browsers will automatically add a white space before and after a paragraph on the web page.

HTML - Headings

Headings:

  • In general, Headings are the title or subtitle given for the content on the web page.
  • Headings in HTML are defined by using a tag <hn> where 'n' refers to the level number 1 to 6.

HTML - Structure of HTML Document

HTML <!DOCTYPE> Declaration:

  • <!DOCTYPE> declaration is an information to the browser about type of document to expect/to understand the version of HTML used in the document. And this <!DOCTYPE> is not an HTML tag.
  • This <!DOCTYPE> declaration is not case sensitive.
  • In HTML5, the declaration of <!DOCTYPE> is very simple.

<!DOCTYPE html>

JavaScript ES6 Enhancement

  • JavaScript was introduced as a client-side scripting language in 1995.

  • ECMAScript (European Computer Manufacturers Association Script) established a standard for scripting languages in 1997.

  • ES is a parent of many scripting languages like TypeScript, JScript, ActionScript, and JavaScript.

  • JavaScript evolved year after year with every new version of ECMAScript introducing new features.

JavaScript Statements

 Statements:

  • Like Every other programming language, JavaScript statements are also the line of instructions that are to be executed by the web browser.
  • In JavaScript, Every statement should be finished with a semicolon ( ; ). 
  • And these statements will be executed in sequential order, from top to bottom.

Javascript Course for Beginners

Why Javascript?
Javascript Course for Beginners
 
    As we all know that we can build beautiful websites using HTML and CSS. But the problem is such pages are static only which means users can just scroll up and down, click on the links. There's no interaction with the users.

Javascript Course for Beginners

    Now we can make these static pages dynamic by adding a layer of interactivity with the help of Javascript.

Introduction to HTML5

 HTML:

Introduction to HTML5

  • HTML stands for HyperText Markup Language.
  • HTML is used for presenting and structuring content on web pages and its standards are maintained by W3C(World wide web Consortium).
  • In general, we use HTML to build a webpage, Hyperlink, Online form, etc.,
  • HTML is case insensitive and platform-independent, the same code will run on a different OS.

Python Quiz

 This Quiz covers the basic concepts of Python

  • Basics of Python 
  • Control Structures
  • Functions
  • Collections
  • Libraries
  • Built-in functions
  • Modules and packages 
  • File and exception handling
  • Control Language (CL) Commands - Quiz

    This Quiz covers the major CL commands used in IBM iSeries/AS400.

    • CL Commands
    • Physical file
    • Logical file
    Total Questions: 10

    Digital Logic Circuit - Quiz #01

    This Quiz covers the below concepts from Digital Logic Circuit

    • Review of Number Systems
    • Binary, Decimal, Octal, HexaDecimal
    • 1's Complement
    • 2's Complement
    • Conversion of Binary code into Gray Code or Viceversa
    • Error detection and Correction codes
    Total Questions: 10

    How to Merge/Combine Partition drive in Windows 10

    • If your drive is getting filled up with files and running into an issue "Not enough free space" and at the same time, there is another drive with plenty of space left. To increase the space, we can merge the drives to solve the issue.
    • For example, if C: drive is getting full but partition D: drive has enough space left. Then you increase the C: drive space by merging C: and D: drive into one.
    • We can do this using the Disk Management tool by deleting the target drive (D:) to unallocate the space. Then Extend the Volume of the source drive (C:) with Extend options.
    • But, Note using the Disk Management tool to merge partitions require us to delete the partition first to create unallocated space. Therefore, you should take back up your data either by manual copy files or using a backup software tool.

    Loop control statements - Break, Continue, Pass in Python

    Break, Continue, Pass in Python:
    • As we know, in Python we have two types of the loop 'for' and 'while' which allows us to iterate over a list, tuple, string, dictionary, and set. 
    • But there are some cases where we want our loop to exit completely or skip a part of the loop or ignores some particular condition. 

    Printer file (PRTF) Design using Report Layout Utility (RLU) in AS400 | iSeries

    Purpose of RLU:

    • To design a report by defining it on the display, saving it as a DDS source, and creating a printer file.
    • Printer file is the same as of spool file which is used for reporting purposes.

    Starting RLU:
    • Enter the source physical file name, library name, and the RLU (printer file) name that we are going to create.
    • We can also specify the page width. By default, it will remain as 132.

    How to create new partition from C: drive in windows 10 without formatting

    • In Windows 10 PC, you have C: drive which contains all program files, in addition, it also has all your saved word documents, photos, and your important files. If your operating system becomes corrupted in case of the worst scenario, then all your important files will get lost.
    • To avoid such data loss and to keep your most important files separate, we will go for a separate space from your C: drive using a partition. By doing this, even if your operating system gets corrupt, we will likely be able to get all your important files safely.
    • It is always safer and best practice to put your personal files or important files on a different partition.
    • This blog post demonstrates how easily we can partition the C: drive using a built-in disk manager in windows 10.

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