Posted in C++/Python

## Python NumPy

Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python.
Besides its obvious scientific uses, Numpy can also be used as an efficient multi-dimensional container of generic data.

#### Arrays in Numpy

Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy, number of dimensions of the array is called rank of the array.A tuple of integers giving the size of the array along each dimension is known as shape of the array. An array class in Numpy is called as ndarray. Elements in Numpy arrays are accessed by using square brackets and can be initialized by using nested Python Lists.

Creating a Numpy Array
Arrays in Numpy can be created by multiple ways, with various number of Ranks, defining the size of the Array. Arrays can also be created with the use of various data types such as lists, tuples, etc. The type of the resultant array is deduced from the type of the elements in the sequences.
Note: Type of array can be explicitly defined while creating the array.

```<code># Python program for</code>
<code># Creation of Arrays</code>
<code>import</code> <code>numpy as np</code>
&nbsp;
<code># Creating a rank 1 Array</code>
<code>arr =</code> <code>np.array([1, 2, 3])</code>
<code>print("Array with Rank 1: \n",arr)</code>
&nbsp;
<code># Creating a rank 2 Array</code>
<code>arr =</code> <code>np.array([[1, 2, 3],</code>
<code>[4, 5, 6]])</code>
<code>print("Array with Rank 2: \n", arr)</code>
&nbsp;
<code># Creating an array from tuple</code>
<code>arr =</code> <code>np.array((1, 3, 2))</code>
<code>print("\nArray created using "</code>
<code>"passed tuple:\n", arr)</code>
```

Output:

```Array with Rank 1:
[1 2 3]
Array with Rank 2:
[[1 2 3]
[4 5 6]]

Array created using passed tuple:
[1 3 2]

```

Accessing the array Index
In a numpy array, indexing or accessing the array index can be done in multiple ways. To print a range of an array, slicing is done. Slicing of an array is defining a range in a new array which is used to print a range of elements from the original array. Since, sliced array holds a range of elements of the original array, modifying content with the help of sliced array modifies the original array content.

```<code># Python program to demonstrate</code>
<code># indexing in numpy array</code>
<code>import</code> <code>numpy as np</code>
&nbsp;
<code># Initial Array</code>
<code>arr =</code> <code>np.array([[-1, 2, 0, 4],</code>
<code>[4, -0.5, 6, 0],</code>
<code>[2.6, 0, 7, 8],</code>
<code>[3, -7, 4, 2.0]])</code>
<code>print("Initial Array: ")</code>
<code>print(arr)</code>
&nbsp;
<code># Printing a range of Array</code>
<code># with the use of slicing method</code>
<code>sliced_arr =</code> <code>arr[:2, ::2]</code>
<code>print</code> <code>("Array with first 2 rows and"</code>
<code>" alternate columns(0 and 2):\n", sliced_arr)</code>
&nbsp;
<code># Printing elements at</code>
<code># specific Indices</code>
<code>Index_arr =</code> <code>arr[[1, 1, 0, 3], </code>
<code>[3, 2, 1, 0]]</code>
<code>print</code> <code>("\nElements at indices (1, 3), "</code>
<code>"(1, 2), (0, 1), (3, 0):\n", Index_arr)</code>
```

Output:

```Initial Array:
[[-1.   2.   0.   4. ]
[ 4.  -0.5  6.   0. ]
[ 2.6  0.   7.   8. ]
[ 3.  -7.   4.   2. ]]
Array with first 2 rows and alternate columns(0 and 2):
[[-1.  0.]
[ 4.  6.]]

Elements at indices (1, 3), (1, 2), (0, 1), (3, 0):
[ 0. 54.  2.  3.]

```
Posted in C++/Python

## Python Pandas

Pandas is an open-source library that is made mainly for working with relational or labeled data both easily and intuitively. It provides various data structures and operations for manipulating numerical data and time series. This library is built on the top of the NumPy library. Pandas is fast and it has high-performance & productivity for users.

Table of Content

• History
• Getting Started
• Series
• DataFrame
• Why Pandas is used for Data Science

## History

Pandas was initially developed by Wes McKinney in 2008 while he was working at AQR Capital Management. He convinced the AQR to allow him to open source the Pandas. Another AQR employee, Chang She, joined as the second major contributor to the library in 2012. Over the time many versions of pandas have been released. The latest version of the pandas is 1.0.1

• Fast and efficient for manipulating and analyzing data.
• Data from different file objects can be loaded.
• Easy handling of missing data (represented as NaN) in floating point as well as non-floating point data
• Size mutability: columns can be inserted and deleted from DataFrame and higher dimensional objects
• Data set merging and joining.
• Flexible reshaping and pivoting of data sets
• Provides time-series functionality.
• Powerful group by functionality for performing split-apply-combine operations on data sets.

## Getting Started

After the pandas has been installed into the system, you need to import the library. This module is generally imported as –

```import pandas as pd
```

Here, pd is referred to as an alias to the Pandas. However, it is not necessary to import the library using alias, it just helps in writing less amount of code everytime a method or property is called.

Posted in C++/Python

## File Handling

In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream available in fstream headerfile.
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.

Now the first step to open the particular file for read or write operation. We can open file by
1. passing file name in constructor at the time of object creation
2. using the open method
For e.g.

Open File by using constructor
ifstream (const char* filename, ios_base::openmode mode = ios_base::in);
ifstream fin(filename, openmode) by default openmode = ios::in
ifstream fin(“filename”);

Open File by using open method
Calling of default constructor
ifstream fin;

fin.open(filename, openmode)
fin.open(“filename”);

Modes :

Default Open Modes :

Below is the implementation by using fstream class.:

``````/* File Handling with C++ using ifstream & ofstream class object*/
/* To write the Content in File*/
/* Then to read the content of file*
#include <iostream>
/* fstream header file for ifstream, ofstream,
fstream classes */
#include <fstream>
using namespace std;

// Creation of ofstream class object
int main()
string line;
ofstream fout;
// by default ios::out mode, automatically deletes
// the content of file. To append the content, open in ios:app
// fout.open("sample.txt", ios::app)
fout.open("sample.txt");

// Execute a loop If file successfully opened
while (fout) {

// Read a Line from standard input
getline(cin, line);

// Press -1 to exit
if (line == "-1")
break;

// Write line in file
fout << line << endl;
}

// Close the File
fout.close();

// Creation of ifstream class object to read the file
ifstream fin;

// by default open mode = ios::in mode
fin.open("sample.txt");

// Execute a loop until EOF (End of File)
while (fin) {

// Read a Line from File
getline(fin, line);

// Print line in Console
cout << line << endl;
}

// Close the file
fin.close();

return 0; ``````
Posted in C++/Python

## Standard Template Library (STL)

The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes, algorithms, and iterators. It is a generalized library and so, its components are parameterized. A working knowledge of template classes is a prerequisite for working with STL.

STL has four components

• Algorithms
• Containers
• Functions
• Iterators

Algorithms

The header algorithm defines a collection of functions especially designed to be used on ranges of elements.They act on containers and provide means for various operations for the contents of the containers.

Containers

Containers or container classes store objects and data. There are in total seven standard “first-class” container classes and three container adaptor classes and only seven header files that provide access to these containers or container adaptors.

• Sequence Containers: implement data structures which can be accessed in a sequential manner.
• Container Adaptors : provide a different interface for sequential containers.
• Associative Containers : implement sorted data structures that can be quickly searched (O(log n) complexity).
• Unordered Associative Containers : implement unordered data structures that can be quickly searched

Functions

The STL includes classes that overload the function call operator. Instances of such classes are called function objects or functors. Functors allow the working of the associated function to be customized with the help of parameters to be passed.

Iterators

As the name suggests, iterators are used for working upon a sequence of values. They are the major feature that allow generality in STL.

Posted in C++/Python

## Constructors & Destructors

What is constructor?
A constructor is a member function of a class which initializes objects of a class. In C++, Constructor is automatically called when object(instance of class) create. It is special member function of the class.
How constructors are different from a normal member function?

A constructor is different from normal functions in following ways:

• Constructor has same name as the class itself
• Constructors don’t have return type
• A constructor is automatically called when an object is created.
• If we do not specify a constructor, C++ compiler generates a default constructor for us (expects no parameters and has an empty body).

Let us understand the types of constructors in C++ by taking a real-world example. Suppose you went to a shop to buy a marker. When you want to buy a marker, what are the options? The first one you go to a shop and say give me a marker. So just saying give me a marker mean that you did not set which brand name and which color, you didn’t mention anything just say you want a marker. So when we said just I want a marker so whatever the frequently sold marker is there in the market or in his shop he will simply hand over that. And this is what a default constructor is! The second method you go to a shop and say I want a marker a red in color and XYZ brand. So you are mentioning this and he will give you that marker. So in this case you have given the parameters. And this is what a parameterized constructor is! Then the third one you go to a shop and say I want a marker like this(a physical marker on your hand). So the shopkeeper will see that marker. Okay, and he will give a new marker for you. So copy of that marker. And that’s what copy constructor is!
Types of Constructors

1. Default Constructors: Default constructor is the constructor which doesn’t take any argument. It has no parameters.
``````
// Cpp program to illustrate the// concept of Constructors

include

using namespace std;

class construct
{
public:
int a, b;
// Default Constructor
construct()
{
a = 10;
b = 20;
}
};

int main()
{
// Default constructor called automatically
// when the object is created
``````
Posted in C++/Python

## Basic Input/Output

In C, we could use the function freopen() to redirect an existing FILE pointer to another stream. The prototype for freopen() is given as

```FILE * freopen ( const char * filename, const char * mode, FILE * stream );

```

For Example to redirect the stdout to say a textfile, we could write

```freopen ("text_file.txt", "w", stdout);

```

While this method is still supported in C++, this article discusses another way to redirect I/O streams.

C++ being an object-oriented programming language gives us the ability to not only define our own streams but also redirect standard streams. Thus in C++, a stream is an object whose behavior is defined by a class. Thus anything that behaves like a stream is also a stream.

Streams Objects in C++ are mainly of three types :

• istream : Stream object of this type can only perform input operations from the stream
• ostream : These objects can only be used for output operations.
• iostream : Can be used for both input and output operations

All these classes, as well as file stream classes, derive from the classes: ios and streambuf. Thus filestream and IO stream objects behave similarly.

All stream objects also have an associated data member of class streambuf. Simply put streambuf object is the buffer for the stream. When we read data from a stream, we don’t read it directly from the source, but instead, we read it from the buffer which is linked to the source. Similarly, output operations are first performed on the buffer, and then the buffer is flushed (written to the physical device) when needed.

C++ allows us to set the stream buffer for any stream. So the task of redirecting the stream simply reduces to changing the stream buffer associated with the stream. Thus the to redirect a Stream A to Stream B we need to do

1. Get the stream buffer of A and store it somewhere
2. Set the stream buffer of A to the stream buffer of B
3. If needed reset the stream buffer of A to its previous stream buffer

We can use the function ios::rdbuf() to perform two opeations.

```1) stream_object.rdbuf(): Returns pointer to the stream buffer of stream_object
2) stream_object.rdbuf(streambuf * p): Sets the stream buffer to the object pointed by p

```

Posted in C++/Python

## Operator

Operators are the foundation of any programming language. Thus the functionality of C/C++ programming language is incomplete without the use of operators. We can define operators as symbols that help us to perform specific mathematical and logical computations on operands. In other words, we can say that an operator operates the operands.
For example, consider the below statement:

`c = a + b;`

Here, ‘+’ is the operator known as addition operator and ‘a’ and ‘b’ are operands. The addition operator tells the compiler to add both of the operands ‘a’ and ‘b’.

C/C++ has many built-in operator types and they are classified as follows:

1. Arithmetic Operators: These are the operators used to perform arithmetic/mathematical operations on operands. Examples: (+, -, *, /, %,++,–). Arithmetic operator are of two types:
1. Unary Operators: Operators that operates or works with a single operand are unary operators. For example: (++ , –)
2. Binary Operators: Operators that operates or works with two operands are binary operators. For example: (+ , – , * , /)
To learn Arithmetic Operators in details visit this link.
2. Relational Operators: These are used for comparison of the values of two operands. For example, checking if one operand is equal to the other operand or not, an operand is greater than the other operand or not etc. Some of the relational operators are (==, >= , <= ). To learn about each of these operators in details go to this link.
3. Logical Operators:  Logical Operators are used to combine two or more conditions/constraints or to complement the evaluation of the original condition in consideration. The result of the operation of a logical operator is a boolean value either true or false. For example, the logical AND represented as ‘&&’ operator in C or C++ returns true when both the conditions under consideration are satisfied. Otherwise it returns false. Therfore, a && b returns true when both a and b are true (i.e. non-zero). To learn about different logical operators in details please visit this link.
4. Bitwise Operators: The Bitwise operators is used to perform bit-level operations on the operands. The operators are first converted to bit-level and then the calculation is performed on the operands. The mathematical operations such as addition, subtraction, multiplication etc. can be performed at bit-level for faster processing. For example, the bitwise AND represented as & operator in C or C++ takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. To learn bitwise operators in details, visit this link.
5. Assignment Operators: Assignment operators are used to assign value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of variable on the left side otherwise the compiler will raise an error.
Different types of assignment operators are shown below:
1. “=”: This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left.
For example:a = 10; b = 20; ch = ‘y’;
2. “+=”: This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current value of the variable on left to the value on right and then assigns the result to the variable on the left.
Example:(a += b) can be written as (a = a + b) If initially value stored in a is 5. Then (a += 6) = 11.
3. “-=”: This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the value on right from the current value of the variable on left and then assigns the result to the variable on the left.
Example:(a -= b) can be written as (a = a – b) If initially value stored in a is 8. Then (a -= 6) = 2.
4. “*=”: This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies the current value of the variable on left to the value on right and then assigns the result to the variable on the left.
Example:(a *= b) can be written as (a = a * b) If initially value stored in a is 5. Then (a *= 6) = 30.
5. “/=”: This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the current value of the variable on left by the value on right and then assigns the result to the variable on the left.
Example:(a /= b) can be written as (a = a / b) If initially value stored in a is 6. Then (a /= 2) = 3.
6. Other Operators: Apart from the above operators there are some other operators available in C or C++ used to perform some specific task. Some of them are discussed here:
1. sizeof operator: sizeof is a much used in the C/C++ programming language. It is a compile time unary operator which can be used to compute the size of its operand. The result of sizeof is of unsigned integral type which is usually denoted by size_t. Basically, sizeof operator is used to compute the size of the variable. To learn about sizeof operator in details you may visit this link.
2. Comma Operator: The comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, it then evaluates the second operand and returns this value (and type). The comma operator has the lowest precedence of any C operator. Comma acts as both operator and separator. To learn about comma in details visit this link.
3. Conditional Operator: Conditional operator is of the form Expression1 ? Expression2 : Expression3 . Here, Expression1 is the condition to be evaluated. If the condition(Expression1) is True then we will execute and return the result of Expression2 otherwise if the condition(Expression1) is false then we will execute and return the result of Expression3. We may replace the use of if..else statements by conditional operators. To learn about conditional operators in details, visit this link.

Operator precedence chart

The below table describes the precedence order and associativity of operators in C / C++ . Precedence of operator decreases from top to bottom.

Posted in C++/Python

## C++

C++ is a general-purpose programming language that was developed as an enhancement of the C language to include object-oriented paradigm. It is an imperative and a compiled language.

C++ is a middle-level language rendering it the advantage of programming low-level (drivers, kernels) and even higher-level applications (games, GUI, desktop apps etc.). The basic syntax and code structure of both C and C++ are the same.

Some of the features & key-points to note about the programming language are as follows:

• Simple: It is a simple language in the sense that programs can be broken down into logical units and parts, has a rich libray support and a variety of data-types.
• Machine Independent but Platform Dependent: A C++ executable is not platform-independent (compiled programs on Linux won’t run on Windows), however they are machine independent.
• Mid-level language: It is a mid-level language as we can do both systems-programming (drivers, kernels, networking etc.) and build large-scale user applications (Media Players, Photoshop, Game Engines etc.)
• Rich library support: Has a rich library support (Both standard ~ built-in data structures, algorithms etc.) as well 3rd party libraries (e.g. Boost libraries) for fast and rapid development.
• Speed of execution: C++ programs excel in execution speed. Since, it is a compiled language, and also hugely procedural. Newer languages have extra in-built default features such as grabage-collection, dynamic typing etc. which slow the execution of the program overall. Since there is no additional processing overhead like this in C++, it is blazing fast.
• Pointer and direct Memory-Access: C++ provides pointer support which aids users to directly manipulate storage address. This helps in doing low-level programming (where one might need to have explicit control on the storage of variables).
• Object-Oriented: One of the strongest points of the language which sets it apart from C. Object-Oriented support helps C++ to make maintainable and extensible programs. i.e. Large-scale applications can be built. Procedural code becomes difficult to maintain as code-size grows.
• Compiled Language: C++ is a compiled language, contributing to its speed.

Applications of C++:
C++ finds varied usage in applications such as:

• Operating Systems & Systems Programming. e.g. Linux-based OS (Ubuntu etc.)
• Browsers (Chrome & Firefox)
• Graphics & Game engines (Photoshop, Blender, Unreal-Engine)
• Database Engines (MySQL, MongoDB, Redis etc.)
• Cloud/Distributed Systems