Friday, March 24, 2017

Perl Questions and Answers

Perl Questions and Answers has been designed with a special intention of helping students and professionals preparing for various Certification Exams and Job Interviews. This section provides a useful collection of sample Interview Questions and Multiple Choice Questions (MCQs) and their answers with appropriate explanations.

Perl - Quick Guide

Perl - Introduction

Perl is a general-purpose programming language originally developed for text manipulation and now used for a wide range of tasks including system administration, web development, network programming, GUI development, and more.

Perl - Functions References

Here is the list of all the important functions supported by standard Perl.
  • abs - absolute value function
  • accept - accept an incoming socket connect
  • alarm - schedule a SIGALRM
  • atan2 - arctangent of Y/X in the range -PI to PI
  • bind - binds an address to a socket

Perl - Useful Resources

The following resources contain additional information on Perl Please use them to get more in-depth knowledge on this topic.

Useful Links on Perl

Discuss Perl

Perl is a programming language developed by Larry Wall, especially designed for text processing. It stands for Practical Extraction and Report Language. It runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.
This tutorial provides a complete understanding on Perl.

NumPy - Introduction

NumPy is a Python package. It stands for 'Numerical Python'. It is a library consisting of multidimensional array objects and a collection of routines for processing of array.
Numeric, the ancestor of NumPy, was developed by Jim Hugunin. Another package Numarray was also developed, having some additional functionalities.

NumPy - Environment

Try it Option Online

We have set up the NumPy Programming environment online, so that you can compile and execute all the available examples online. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it online.

NumPy - Ndarray Object

The most important object defined in NumPy is an N-dimensional array type called ndarray. It describes the collection of items of the same type. Items in the collection can be accessed using a zero-based index.
Every item in an ndarray takes the same size of block in the memory. Each element in ndarray is an object of data-type object (called dtype).

NumPy - Data Types

NumPy supports a much greater variety of numerical types than Python does. The following table shows different scalar data types defined in NumPy.
S.No Data Types & Description
1. bool_
Boolean (True or False) stored as a byte

NumPy - Array Attributes

In this chapter, we will discuss the various array attributes of NumPy.

ndarray.shape

This array attribute returns a tuple consisting of array dimensions. It can also be used to resize the array.

Example 1

import numpy as np 
a = np.array([[1,2,3],[4,5,6]]) 
print a.shape
The output is as follows −
(2, 3)

NumPy - Array Creation Routines

A new ndarray object can be constructed by any of the following array creation routines or using a low-level ndarray constructor.

numpy.empty

It creates an uninitialized array of specified shape and dtype. It uses the following constructor −
numpy.empty(shape, dtype = float, order = 'C')
The constructor takes the following parameters.

NumPy - Array From Existing Data

In this chapter, we will discuss how to create an array from existing data.

numpy.asarray

This function is similar to numpy.array except for the fact that it has fewer parameters. This routine is useful for converting Python sequence into ndarray.
numpy.asarray(a, dtype = None, order = None)
The constructor takes the following parameters.

NumPy - Array From Numerical Ranges

In this chapter, we will see how to create an array from numerical ranges.

numpy.arange

This function returns an ndarray object containing evenly spaced values within a given range. The format of the function is as follows −
numpy.arange(start, stop, step, dtype)
The constructor takes the following parameters.

NumPy - Indexing & Slicing

Contents of ndarray object can be accessed and modified by indexing or slicing, just like Python's in-built container objects.
As mentioned earlier, items in ndarray object follows zero-based index. Three types of indexing methods are available − field access, basic slicing and advanced indexing.

NumPy - Advanced Indexing

It is possible to make a selection from ndarray that is a non-tuple sequence, ndarray object of integer or Boolean data type, or a tuple with at least one item being a sequence object. Advanced indexing always returns a copy of the data. As against this, the slicing only presents a view.
There are two types of advanced indexing − Integer and Boolean.

NumPy - Broadcasting

The term broadcasting refers to the ability of NumPy to treat arrays of different shapes during arithmetic operations. Arithmetic operations on arrays are usually done on corresponding elements. If two arrays are of exactly the same shape, then these operations are smoothly performed.

NumPy - Iterating Over Array

NumPy package contains an iterator object numpy.nditer. It is an efficient multidimensional iterator object using which it is possible to iterate over an array. Each element of an array is visited using Python’s standard Iterator interface.
Let us create a 3X4 array using arange() function and iterate over it using nditer.

NumPy - Array Manipulation

Several routines are available in NumPy package for manipulation of elements in ndarray object. They can be classified into the following types −

Changing Shape

S.No Shape & Description
1. reshape Gives a new shape to an array without changing its data

NumPy - Binary Operators

Following are the functions for bitwise operations available in NumPy package.
S.No Operation & Description
1. bitwise_and Computes bitwise AND operation of array elements

NumPy - String Functions

The following functions are used to perform vectorized string operations for arrays of dtype numpy.string_ or numpy.unicode_. They are based on the standard string functions in Python's built-in library.

NumPy - Mathematical Functions

Quite understandably, NumPy contains a large number of various mathematical operations. NumPy provides standard trigonometric functions, functions for arithmetic operations, handling complex numbers, etc.

NumPy - Arithmetic Operations

Input arrays for performing arithmetic operations such as add(), subtract(), multiply(), and divide() must be either of the same shape or should conform to array broadcasting rules.

Example

import numpy as np 
a = np.arange(9, dtype = np.float_).reshape(3,3) 

NumPy - Statistical Functions

NumPy has quite a few useful statistical functions for finding minimum, maximum, percentile standard deviation and variance, etc. from the given elements in the array. The functions are explained as follows −

NumPy - Sort, Search & Counting Functions

A variety of sorting related functions are available in NumPy. These sorting functions implement different sorting algorithms, each of them characterized by the speed of execution, worst case performance, the workspace required and the stability of algorithms. Following table shows the comparison of three sorting algorithms.

NumPy - Byte Swapping

We have seen that the data stored in the memory of a computer depends on which architecture the CPU uses. It may be little-endian (least significant is stored in the smallest address) or big-endian (most significant byte in the smallest address).

NumPy - Copies & Views

While executing the functions, some of them return a copy of the input array, while some return the view. When the contents are physically stored in another location, it is called Copy. If on the other hand, a different view of the same memory content is provided, we call it as View.

NumPy - Matrix Library

NumPy package contains a Matrix library numpy.matlib. This module has functions that return matrices instead of ndarray objects.

matlib.empty()

The matlib.empty() function returns a new matrix without initializing the entries. The function takes the following parameters.
numpy.matlib.empty(shape, dtype, order)
Where,

NumPy - Linear Algebra

NumPy package contains numpy.linalg module that provides all the functionality required for linear algebra. Some of the important functions in this module are described in the following table.
S.No Function & Description
1. dot Dot product of the two arrays

NumPy - Matplotlib

Matplotlib is a plotting library for Python. It is used along with NumPy to provide an environment that is an effective open source alternative for MatLab. It can also be used with graphics toolkits like PyQt and wxPython.
Matplotlib module was first written by John D. Hunter. Since 2012, Michael Droettboom is the principal developer. Currently, Matplotlib ver. 1.5.1 is the stable version available. The package is available in binary distribution as well as in the source code form on www.matplotlib.org.

NumPy - Histogram Using Matplotlib

NumPy has a numpy.histogram() function that is a graphical representation of the frequency distribution of data. Rectangles of equal horizontal size corresponding to class interval called bin and variable height corresponding to frequency.

I/O with NumPy

The ndarray objects can be saved to and loaded from the disk files. The IO functions available are −
  • load() and save() functions handle /numPy binary files (with npy extension)
  • loadtxt() and savetxt() functions handle normal text files

NumPy - Quick Guide

NumPy - Introduction

NumPy is a Python package. It stands for 'Numerical Python'. It is a library consisting of multidimensional array objects and a collection of routines for processing of array.
Numeric, the ancestor of NumPy, was developed by Jim Hugunin. Another package Numarray was also developed, having some additional functionalities.

NumPy - Useful Resources

The following resources contain additional information on NumPy. Please use them to get more in-depth knowledge on this.

Discuss NumPy

NumPy, which stands for Numerical Python, is a library consisting of multidimensional array objects and a collection of routines for processing those arrays. Using NumPy, mathematical and logical operations on arrays can be performed. This tutorial explains the basics of NumPy such as its architecture and environment. It also discusses the various array functions, types of indexing, etc. An introduction to Matplotlib is also provided. All this is explained with the help of examples for better understanding.

Lua - Overview

Lua is an extensible, light-weight programming language written in C. It started as an in-house project in 1993 by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, and Waldemar Celes.
It was designed from the beginning to be a software that can be integrated with the code written in C and other conventional languages.

Lua - Environment

Try it Option Online

We have set up the Lua Programming environment online, so that you can compile and execute all the available examples online. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it online.

Lua - Basic Syntax

Let us start creating our first Lua program!

First Lua Program

Interactive Mode Programming

Lua provides a mode called interactive mode. In this mode, you can type in instructions one after the other and get instant results. This can be invoked in the shell by using the lua -i or just the lua command. Once you type in this, press Enter and the interactive mode will be started as shown below.

Lua - Variables

A variable is nothing but a name given to a storage area that our programs can manipulate. It can hold different types of values including functions and tables.
The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Lua is case-sensitive. There are eight basic types of values in Lua −

Lua - Data Types

Lua is a dynamically typed language, so the variables don't have types, only the values have types. Values can be stored in variables, passed as parameters and returned as results.
In Lua, though we don't have variable data types, but we have types for the values. The list of data types for values are given below.

Lua - Operators

An operator is a symbol that tells the interpreter to perform specific mathematical or logical manipulations. Lua language is rich in built-in operators and provides the following type of operators −
  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Misc Operators

Lua - Loops

There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially − the first statement in a function is executed first, followed by the second, and so on.

Lua - Decision Making

Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed, if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

Lua - Functions

A function is a group of statements that together perform a task. You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division usually unique, is so each function performs a specific task.

Lua - Strings

String is a sequence of characters as well as control characters like form feed. String can be initialized with three forms which includes −
  • Characters between single quotes
  • Characters between double quotes
  • Characters between [[ and ]]

Lua - Arrays

Arrays are ordered arrangement of objects, which may be a one dimensional array containing a collection of rows or a multi-dimensional array containing multiple rows and columns.
In Lua, arrays are implemented using indexing tables with integers. The size of an array is not fixed and it can grow based on our requirements, subject to memory constraints.

Lua - Iterators

Iterator is a construct that enables you to traverse through the elements of the so called collection or container. In Lua, these collections often refer to tables, which are used to create various data structures like array.

Lua - Tables

Introduction

Tables are the only data structure available in Lua that helps us create different types like arrays and dictionaries. Lua uses associative arrays and which can be indexed with not only numbers but also with strings except nil. Tables have no fixed size and can grow based on our need.

Lua - Modules

What is a Module?

Module is like a library that can be loaded using require and has a single global name containing a table. This module can consist of a number of functions and variables. All these functions and variables are wrapped in to the table which acts as a namespace. Also a well behaved module has necessary provisions to return this table on require.

Lua - Metatables

A metatable is a table that helps in modifying the behavior of a table it is attached to with the help of a key set and related meta methods. These meta methods are powerful Lua functionality that enables features like, −
  • Changing/adding functionalities to operators on tables.
  • Looking up metatables when the key is not available in the table using __index in metatable.

Lua - Coroutines

Introduction

Coroutines are collaborative in nature, which allows two or more methods to execute in a controlled manner. With coroutines, at any given time, only one coroutine runs and this running coroutine only suspends its execution when it explicitly requests to be suspended.

Lua - File I/O

I/O library is used for reading and manipulating files in Lua. There are two kinds of file operations in Lua namely implicit file descriptors and explicit file descriptors.
For the following examples, we will use a sample file test.lua as shown below.
-- sample test.lua
-- sample2 test.lua

Lua - Error Handling

Need for Error Handling

Error handling is quite critical since real-world operations often require the use of complex operations, which includes file operations, database transactions and web service calls.
In any programming, there is always a requirement for error handling. Errors can be of two types which includes,