The Best College Academy of Our Small City

Latest News - QUIS NOSTRUM - Exercitationem ullam corporis suscipit laboriosam

Learn Phyton [Environment Setup]

Friday, January 17, 2020

 Python is available on a wide variety of platforms including Linux and Mac OS X. Let's understand how to set up our Python environment.
Local Environment Setup
Open a terminal window and type "python" to find out if it is already installed and which version is installed.
* Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX, etc.)
* Win 9x/NT/2000
* Macintosh (Intel, PPC, 68K)
OS/2
* DOS (multiple versions)
* PalmOS
* Nokia mobile phones
* Windows CE
* Acorn/RISC OS
* BeOS
* Amiga
* VMS/OpenVMS
* QNX
* VxWorks
* Psion
* Python has also been ported to the Java and .NET virtual machines

Getting Python
The most up-to-date and current source code, binaries, documentation, news, etc., is available on the official website of Python https://www.python.org/

You can download Python documentation from https://www.python.org/doc/. The documentation is available in HTML, PDF, and PostScript formats.

Installing Python
Python distribution is available for a wide variety of platforms. You need to download only the binary code applicable for your platform and install Python.
If the binary code for your platform is not available, you need a C compiler to compile the source code manually. Compiling the source code offers more flexibility in terms of choice of features that you require in your installation.
Here is a quick overview of installing Python on various platforms −

Unix and Linux Installation

Here are the simple steps to install Python on Unix/Linux machine.
* Open a Web browser and go to https://www.python.org/downloads/.
* Follow the link to download zipped source code available for Unix/Linux.
* Download and extract files.
* Editing the Modules/Setup file if you want to customize some options.
* run ./configure script
* make
* make install
This installs Python at standard location /usr/local/bin and its libraries at /usr/local/lib/pythonXX where XX is the version of Python.

Windows Installation
Here are the steps to install Python on Windows machine.
* Open a Web browser and go to https://www.python.org/downloads/.
* Follow the link for the Windows installer python-XYZ.msifile where XYZ is the version you need to install.
* To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save the installer file to your local machine and then run it to find out if your machine supports MSI.
* Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is finished, and you are done.

Macintosh Installation
Recent Macs come with Python installed, but it may be several years out of date. See http://www.python.org/download/mac/for instructions on getting the current version along with extra tools to support development on the Mac. For older Mac OS's before Mac OS X 10.3 (released in 2003), MacPython is available.
Jack Jansen maintains it and you can have full access to the entire documentation at his website − http://www.cwi.nl/~jack/macpython.html. You can find complete installation details for Mac OS installation.

Setting up PATH
Programs and other executable files can be in many directories, so operating systems provide a search path that lists the directories that the OS searches for executables.
The path is stored in an environment variable, which is a named string maintained by the operating system. This variable contains information available to the command shell and other programs.
The path variable is named as PATH in Unix or Path in Windows (Unix is case sensitive; Windows is not).
In Mac OS, the installer handles the path details. To invoke the Python interpreter from any particular directory, you must add the Python directory to your path.

Setting path at Unix/Linux
To add the Python directory to the path for a particular session in Unix −
* In the csh shell − type setenv PATH "$PATH:/usr/local/bin/python" and press Enter.
* In the bash shell (Linux) − type export ATH="$PATH:/usr/local/bin/python" and press Enter.
* In the sh or ksh shell − type PATH="$PATH:/usr/local/bin/python" and press Enter.
* Note − /usr/local/bin/python is the path of the Python directory

Setting path at Windows
To add the Python directory to the path for a particular session in Windows −

At the command prompt − type path %path%;C:\Python and press Enter.

Note − C:\Python is the path of the Python directory
Python Environment Variables
Here are important environment variables, which can be recognized by Python −

1- PYTHONPATH
It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer.
2- PYTHONSTARTUP
It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains commands that load utilities or modify PYTHONPATH.
3- PYTHONCASEOK
It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it.
4- PYTHONHOME
It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy.

Running Python
There are three different ways to start Python −
Interactive Interpreter
You can start Python from Unix, DOS, or any other system that provides you a command-line interpreter or shell window.
Enter python the command line.
Start coding right away in the interactive interpreter.

$python # Unix/Linux
or
python% # Unix/Linux
or
C:> python # Windows/DOS

Here is the list of all the available command line options −

1. -d
It provides debug output.
2. -O
It generates optimized bytecode (resulting in .pyo files).
3. -S
Do not run import site to look for Python paths on startup.
4. -v
verbose output (detailed trace on import statements).
5. -X
disable class-based built-in exceptions (just use strings); obsolete starting with version 1.6.
6. -c cmd
run Python script sent in as cmd string
7. file
run Python script from given file

Script from the Command-line
A Python script can be executed at command line by invoking the interpreter on your application, as in the following −

$python script.py # Unix/Linux

or

python% script.py # Unix/Linux

or

C: >python script.py # Windows/DOS

Note − Be sure the file permission mode allows execution.

Integrated Development Environment
You can run Python from a Graphical User Interface (GUI) environment as well, if you have a GUI application on your system that supports Python.
* Unix − IDLE is the very first Unix IDE for Python.
* Windows − PythonWin is the first Windows interface for Python and is an IDE with a GUI.
* Macintosh − The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files.

If you are not able to set up the environment properly, then you can take help from your system admin. Make sure the Python environment is properly set up and working perfectly fine.

Note − All the examples given in subsequent chapters are executed with Python 2.4.3 version available on CentOS flavor of Linux.

We already have set up Python Programming environment online, so that you can execute all the available examples online at the same time when you are learning theory. Feel free to modify any example and execute it online.

Overview of Python Programming Language

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.
Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is similar to PERL and PHP.
Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter directly to write your programs.
Python is Object-Oriented − Python supports Object-Oriented style or technique of programming that encapsulates code within objects.
Python is a Beginner's Language − Python is a great language for the beginner-level programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games.

History of Python

Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public License (GPL).
Python is now maintained by a core development team at the institute, although Guido van Rossum still holds a vital role in directing its progress.

Python Features

Python's features include −
*  Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language quickly.
*  Easy-to-read − Python code is more clearly defined and visible to the eyes.
*  Easy-to-maintain − Python's source code is fairly easy-to-maintain.
*  A broad standard library − Python's bulk of the library is very portable and cross-platform compatible on UNIX, Windows, and Macintosh.
*  Interactive Mode − Python has support for an interactive mode which allows interactive testing and debugging of snippets of code.
*  Portable − Python can run on a wide variety of hardware platforms and has the same interface on all platforms.
*  Extendable − You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient.
*  Databases − Python provides interfaces to all major commercial databases.
*  GUI Programming − Python supports GUI applications that can be created and ported to many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix.
*  Scalable − Python provides a better structure and support for large programs than shell scripting.

Apart from the above-mentioned features, Python has a big list of good features, few are listed below −
*  It supports functional and structured programming methods as well as OOP.
*  It can be used as a scripting language or can be compiled to byte-code for building large applications.
*  It provides very high-level dynamic data types and supports dynamic type checking.
*  IT supports automatic garbage collection.
*  It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

Circle Generation Algorithm

Wednesday, January 15, 2020

Drawing a circle on the screen is a little complex than drawing a line. There are two popular algorithms for generating a circle − Bresenham’s Algorithm and Midpoint Circle Algorithm. These algorithms are based on the idea of determining the subsequent points required to draw the circle. Let us discuss the algorithms in detail −

The equation of circle is X2+Y2=r2,X2+Y2=r2, where r is radius.
Circle Generation

Bresenham’s Algorithm
We cannot display a continuous arc on the raster display. Instead, we have to choose the nearest pixel position to complete the arc.

From the following illustration, you can see that we have put the pixel at (X, Y) location and now need to decide where to put the next pixel − at N (X+1, Y) or at S (X+1, Y-1).


This can be decided by the decision parameter d.

If d <= 0, then N(X+1, Y) is to be chosen as next pixel.
If d > 0, then S(X+1, Y-1) is to be chosen as the next pixel.
Algorithm
Step 1 − Get the coordinates of the center of the circle and radius, and store them in x, y, and R respectively. Set P=0 and Q=R.

Step 2 − Set decision parameter D = 3 – 2R.

Step 3 − Repeat through step-8 while X < Y.

Step 4 − Call Draw Circle (X, Y, P, Q).

Step 5 − Increment the value of P.

Step 6 − If D < 0 then D = D + 4P + 6.

Step 7 − Else Set Y = Y - 1, D = D + 4(P-Q) + 10.

Step 8 − Call Draw Circle (X, Y, P, Q).

Draw Circle Method(X, Y, P, Q).

Call Putpixel (X + P, Y + Q).
Call Putpixel (X - P, Y + Q).
Call Putpixel (X + P, Y - Q).
Call Putpixel (X - P, Y - Q).
Call Putpixel (X + Q, Y + X).
Call Putpixel (X - Q, Y + X).
Call Putpixel (X + Q, Y - X).
Call Putpixel (X - Q, Y - X).
Mid Point Algorithm
Step 1 − Input radius r and circle center (xc,yc)(xc,yc) and obtain the first point on the circumference of the circle centered on the origin as
(x0, y0) = (0, r)
Step 2 − Calculate the initial value of decision parameter as

P0P0 = 5/4 – r (See the following description for simplification of this equation.)
f(x, y) = x2 + y2 - r2 = 0

f(xi - 1/2 + e, yi + 1)
        = (xi - 1/2 + e)2 + (yi + 1)2 - r2
        = (xi- 1/2)2 + (yi + 1)2 - r2 + 2(xi - 1/2)e + e2
        = f(xi - 1/2, yi + 1) + 2(xi - 1/2)e + e2 = 0
Midpoint Algorithm

Let di = f(xi - 1/2, yi + 1) = -2(xi - 1/2)e - e2
Thus,

If e < 0 then di > 0 so choose point S = (xi - 1, yi + 1).
di+1 = f(xi - 1 - 1/2, yi + 1 + 1) = ((xi - 1/2) - 1)2 + ((yi + 1) + 1)2 - r2
        = di - 2(xi - 1) + 2(yi + 1) + 1
        = di + 2(yi + 1 - xi + 1) + 1
                               
If e >= 0 then di <= 0 so choose point T = (xi, yi + 1)
   di+1 = f(xi - 1/2, yi + 1 + 1)
       = di + 2yi+1 + 1
                               
The initial value of di is
   d0 = f(r - 1/2, 0 + 1) = (r - 1/2)2 + 12 - r2
      = 5/4 - r {1-r can be used if r is an integer}
                             
When point S = (xi - 1, yi + 1) is chosen then
   di+1 = di + -2xi+1 + 2yi+1 + 1
             
When point T = (xi, yi + 1) is chosen then
   di+1 = di + 2yi+1 + 1
Step 3 − At each XKXK position starting at K=0, perform the following test −
If PK < 0 then next point on circle (0,0) is (XK+1,YK) and
   PK+1 = PK + 2XK+1 + 1
Else
   PK+1 = PK + 2XK+1 + 1 – 2YK+1
             
Where, 2XK+1 = 2XK+2 and 2YK+1 = 2YK-2.
Step 4 − Determine the symmetry points in other seven octants.

Step 5 − Move each calculate pixel position (X, Y) onto the circular path centered on (XC,YC)(XC,YC) and plot the coordinationnate values.
X = X + XC, Y = Y + YC
Step 6 − Repeat step-3 through 5 until X >= Y.

Line Generation Algorithm

A line connects two points. It is a basic element in graphics. To draw a line, you need two points between which you can draw a line. In the following three algorithms, we refer the one point of line as X0,Y0X0,Y0 and the second point of line as X1,Y1X1,Y1.

DDA Algorithm

Digital Differential Analyzer (DDA) algorithm is the simple line generation algorithm which is explained step by step here.
Step 1 − Get the input of two end points (X0,Y0)(X0,Y0) and (X1,Y1)(X1,Y1).
Step 2 − Calculate the difference between two end points.
dx = X1 - X0
dy = Y1 - Y0
Step 3 − Based on the calculated difference in step-2, you need to identify the number of steps to put pixel. If dx > dy, then you need more steps in x coordinate; otherwise in y coordinate.
if (absolute(dx) > absolute(dy))
   Steps = absolute(dx);
else
   Steps = absolute(dy);
Step 4 − Calculate the increment in x coordinate and y coordinate.
Xincrement = dx / (float) steps;
Yincrement = dy / (float) steps;
Step 5 − Put the pixel by successfully incrementing x and y coordinates accordingly and complete the drawing of the line.
for(int v=0; v < Steps; v++)
{
   x = x + Xincrement;
   y = y + Yincrement;
   putpixel(Round(x), Round(y));
}

Bresenham’s Line Generation

The Bresenham algorithm is another incremental scan conversion algorithm. The big advantage of this algorithm is that, it uses only integer calculations. Moving across the x axis in unit intervals and at each step choose between two different y coordinates.
For example, as shown in the following illustration, from position (2, 3) you need to choose between (3, 3) and (3, 4). You would like the point that is closer to the original line.
At sample position Xk+1,Xk+1, the vertical separations from the mathematical line are labelled as dupperdupper and dlowerdlower.
From the above illustration, the y coordinate on the mathematical line at xk+1xk+1 is −
Y = m(XkXk+1) + b
So, dupperdupper and dlowerdlower are given as follows −
dlower=yykdlower=y−yk
=m(Xk+1)+bYk=m(Xk+1)+b−Yk
and
dupper=(yk+1)−ydupper=(yk+1)−y
=Yk+1m(Xk+1)−b=Yk+1−m(Xk+1)−b
You can use these to make a simple decision about which pixel is closer to the mathematical line. This simple decision is based on the difference between the two pixel positions.
dlowerdupper=2m(xk+1)−2yk+2b1dlower−dupper=2m(xk+1)−2yk+2b−1
Let us substitute m with dy/dx where dx and dy are the differences between the end-points.
dx(dlowerdupper)=dx(2dydx(xk+1)−2yk+2b1)dx(dlower−dupper)=dx(2dydx(xk+1)−2yk+2b−1)
=2dy.xk2dx.yk+2dy+2dx(2b1)=2dy.xk−2dx.yk+2dy+2dx(2b−1)
=2dy.xk2dx.yk+C=2dy.xk−2dx.yk+C
So, a decision parameter PkPk for the kth step along a line is given by −
pk=dx(dlowerdupper)pk=dx(dlower−dupper)
=2dy.xk2dx.yk+C=2dy.xk−2dx.yk+C
The sign of the decision parameter PkPk is the same as that of dlowerdupperdlower−dupper.
If pkpk is negative, then choose the lower pixel, otherwise choose the upper pixel.
Remember, the coordinate changes occur along the x axis in unit steps, so you can do everything with integer calculations. At step k+1, the decision parameter is given as −
pk+1=2dy.xk+12dx.yk+1+Cpk+1=2dy.xk+1−2dx.yk+1+C
Subtracting pkpk from this we get −
pk+1pk=2dy(xk+1xk)−2dx(yk+1yk)pk+1−pk=2dy(xk+1−xk)−2dx(yk+1−yk)
But, xk+1xk+1 is the same as (xk)+1(xk)+1. So −
pk+1=pk+2dy2dx(yk+1yk)pk+1=pk+2dy−2dx(yk+1−yk)
Where, Yk+1YkYk+1–Yk is either 0 or 1 depending on the sign of PkPk.
The first decision parameter p0p0 is evaluated at (x0,y0)(x0,y0) is given as −
p0=2dydxp0=2dy−dx
Now, keeping in mind all the above points and calculations, here is the Bresenham algorithm for slope m < 1 −
Step 1 − Input the two end-points of line, storing the left end-point in (x0,y0)(x0,y0).
Step 2 − Plot the point (x0,y0)(x0,y0).
Step 3 − Calculate the constants dx, dy, 2dy, and (2dy – 2dx) and get the first value for the decision parameter as −
p0=2dydxp0=2dy−dx
Step 4 − At each XkXk along the line, starting at k = 0, perform the following test −
If pkpk < 0, the next point to plot is (xk+1,yk)(xk+1,yk) and
pk+1=pk+2dypk+1=pk+2dy
Otherwise,
(xk,yk+1)(xk,yk+1)
pk+1=pk+2dy2dxpk+1=pk+2dy−2dx
Step 5 − Repeat step 4 (dx – 1) times.
For m > 1, find out whether you need to increment x while incrementing y each time.
After solving, the equation for decision parameter PkPk will be very similar, just the x and y in the equation gets interchanged.

Mid-Point Algorithm

Mid-point algorithm is due to Bresenham which was modified by Pitteway and Van Aken. Assume that you have already put the point P at (x, y) coordinate and the slope of the line is 0 ≤ k ≤ 1 as shown in the following illustration.

Now you need to decide whether to put the next point at E or N. This can be chosen by identifying the intersection point Q closest to the point N or E. If the intersection point Q is closest to the point N then N is considered as the next point; otherwise E.
To determine that, first calculate the mid-point M(x+1, y + ½). If the intersection point Q of the line with the vertical line connecting E and N is below M, then take E as the next point; otherwise take N as the next point.
In order to check this, we need to consider the implicit equation −
F(x,y) = mx + b - y
For positive m at any given X,
  • If y is on the line, then F(x, y) = 0
  • If y is above the line, then F(x, y) < 0
  • If y is below the line, then F(x, y) > 0