Archive for the ‘Programming’ Category

Hi guys, this is a post on creating a simple text mode menu in Python 2.7.x. Hope this helps! Below is the output of the sample menu that we will be creating:

Sample Menu

------------------------------ MENU ------------------------------
1. Menu Option 1
2. Menu Option 2
3. Menu Option 3
4. Menu Option 4
5. Exit
-------------------------------------------------------------------
Enter your choice [1-5]: 

Here we have a function print_menu() which is used only to print the menu and the options available. This function does not take any inputs.

The source we have here creates a menu with 5 options with the 5th option to exit the menu.

Here, we create a Boolean variable named “loop” and set its value to “True“. Then we create a while loop which will run until the value of “loop” is “False”.

And within the while loop, we call the function print_menu() in which the user is presented with a menu and the list of options. We now request the user input and store it in a variable named “choice” [NOTE: The input must be a number and not any character or else it will through a error].

Now, we use create if statements to check the value of choice. For example: the first if statement checks if choice==1 and if it prints “Menu 1 has been selected”. Similar, We make use of elif statements to check other values of choice.

And when choice==5, we change the value of “loop” to “False” , which will end the while loop as it will only run when the value of “loop” is “True“.

Finally, for all other numbers other than 1,2,3,4 and 5, we simply print and error message and requests the user to enter a valid input and to try again.

Source Code:

## Text menu in Python
     
def print_menu():       ## Your menu design here
    print 30 * "-" , "MENU" , 30 * "-"
    print "1. Menu Option 1"
    print "2. Menu Option 2"
    print "3. Menu Option 3"
    print "4. Menu Option 4"
    print "5. Exit"
    print 67 * "-"
 
loop=True       
 
while loop:          ## While loop which will keep going until loop = False
    print_menu()    ## Displays menu
    choice = input("Enter your choice [1-5]: ")
    
    if choice==1:     
        print "Menu 1 has been selected"
        ## You can add your code or functions here
    elif choice==2:
        print "Menu 2 has been selected"
        ## You can add your code or functions here
    elif choice==3:
        print "Menu 3 has been selected"
        ## You can add your code or functions here
    elif choice==4:
        print "Menu 4 has been selected"
        ## You can add your code or functions here
    elif choice==5:
        print "Menu 5 has been selected"
        ## You can add your code or functions here
        loop=False # This will make the while loop to end as not value of loop is set to False
    else:
        # Any integer inputs other than values 1-5 we print an error message
        raw_input("Wrong option selection. Enter any key to try again..")

Feel feel to leave a comment if you have any queries or want to reach out to me. You can also Follow/Subscribe to my blog to get future blog posts! Happy Bloggin! 🙂

Regards
ΞXΤЯΞМΞ

This is a quick tutorial on reverse loops in Python 2.7.x  and also will be showing you an example on how to reverse a list. There are many methods you can do achieve this. In this tutorial, we will not be using the list.reverse() method which is simpler but will be using a simple loop and another method i.e. using the reversed() function to learn more about reverse loops.Hope this helps!

Lets say we have some numbers stored in a list (u can make use of any random numbers, here I have used numbers 0-9 for simplicity) as follows:

number_list= [0,1,2,3,4,5,6,7,8,9]

And now if we need to store & display these numbers in reverse order, we can use the reverse loop as follows:

## Reverse Loops in Python 2.7.x
number_list= [0,1,2,3,4,5,6,7,8,9]       ## Sample list 

print "Original List = ", number_list  ## Displays list

reversed_list=[]        ## Create an empty list named reversed_list

for item in number_list[::-1]:      ## Reverse Loop
    reversed_list.append(item)      ## Add/Append current item to reversed_list

print "Reversed List = ", reversed_list ## Print Reversed List

Output:

Original List =  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Reversed List =  [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Alternative Method  (using reversed function):

Consider the below list:

number_list= [0,1,2,3,4,5,6,7,8,9]

First, we will calculate the size/length of the list, by using the function len() and storing it into a variable size_of_list

size_of_list=len(number_list)

Here, the value of  the size_of_list will be 10.

[NOTE :Here range(10) will be a list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] . And we use reversed(range(10)) function to reverse the values of range list, and then use the for loop to assign the first value of item as 9, second value as 8 and so on. ]

## Reverse Loop in Python 2.7.x using reversed function

number_list= [0,1,2,3,4,5,6,7,8,9]       ## Sample list
print "Original List = ", number_list  ## Displays list

reversed_list=[]            ## Create an empty list named reversed_list
size_of_list=len(number_list) ## Store Size/length of list , (here length is 10)

for item in reversed(range(size_of_list)): ## Reverse loop
    reversed_list.append(number_list[item]) ## Add/Append current item to reversed_list

print "Reversed List = " , reversed_list  ## Print Reversed List

Output:

Orginal List =  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Reversed List =  [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Feel feel to leave a comment if you have any queries or want to reach out to me. You can also Follow/Subscribe to my blog to get future blog posts! Happy Bloggin! 🙂

Regards
ΞXΤЯΞМΞ

This is a simple guide on installing Python 2.7.8 in Windows 8.1 operating system with screenshots.

Requirements:

  1. Windows 8.1 / Windows 8 OS
  2. Python 2.7.8 : Download Link (~15.92 MB)

Step 1: Installation

Download the python setup file mentioned above and run the installer.

 

installer window picture

Click “Next”.

2

Leave it to the defaults and then click “Next“,

installation directory picture

Now in customize screen, you may see a RED X next to “Add python.exe to Path”.

Customization Screen picture

Click on the RED X and then select the first option option “Will be installed on local hard drive”.

custom selection picture

So finally you will have the below screen:

customization final

Then click on “Next“, and follow the on screen instructions:

progress picture

Finally, click on “Finish“.

python installation complete

 

Step 2: Running the Python Interpreter.

Now, to open Python Interpreter in your Windows 8.1 machine, Press Windows key+X (Press Windows key and while pressing CTRL , tap the letter R once) , you will see a context menu (shown below), click on “Command Prompt (Admin)“. (Click Yes if prompted from User Account Control)

cmd run as admin picture

You will now see the windows command prompt window as shown below:

command prompt admin window picture

Now, type python and then “Enter” in your keyboard to start using the DOS interactive python interpreter.

12

Now, you test it by writing a simple print statement, such as:

print “Hi EXTR3ME”

and then hit “Enter“, you will see the output in the next line as shown below:

python dos shell output

You should have by now installed Python 2.7.8 in your Windows 8/8.1 systems and also written a sample program to test it.

Hope this helps. Feel free to leave a comment below or if have any further queries. 

Don’t forget to subscribe to get future updates! 🙂

Regards
ΞXΤЯ3МΞ

This is a guide on how we can generate Stirling numbers using Python programming language.

Stirling Number S(n,k) :

A Stirling Number of the second kind, S(n, k), is the number of ways of splitting “n” items in “k” non-empty sets.

The formula used for calculating Stirling Number is:

S(n, k) = k* S(n-1, k) + S(n-1, k-1)

 
Example 1:

If you want to split a group of 3 items into 2 groups where {A, B, C} are the elements, and {Group 1} and {Group 2} are two groups, you can split them are follows:

{Group 1}                    {Group 2}

A, B                                    C

A                                        B, C

B                                        A, C

So, the number of ways of splitting 3 items into 2 groups = 3.

Therefore,  the Stirling number , S(3, 2) = 3

Example 2:

If you want to split a group of 5 elements into 2 groups where {A,B,C,D,E} are the items and {Group 1} and {Group 2} are two groups, it can be done in a total of 7 ways. So,

S(4, 2) = 7

Code:
This is the code that I have written to generate Stirling Numbers.

# Stirling Algorithm
# Cod3d by EXTR3ME
# https://extr3metech.wordpress.com

def stirling(n,k):
    n1=n
    k1=k
    if n<=0:
        return 1
    
    elif k<=0:
        return 0
    
    elif (n==0 and k==0):
        return -1
    
    elif n!=0 and n==k:
        return 1
    
    elif n<k:
        return 0

    else:
        temp1=stirling(n1-1,k1)
        temp1=k1*temp1
        return (k1*(stirling(n1-1,k1)))+stirling(n1-1,k1-1)

print   stirling(1,1)
# Output = 1

print stirling(5,2)
# Output  = 15

print stirling(5,3)
# Output  = 25

print stirling(5,4)
# Output  = 10

print stirling(5,5)
# Output  = 1

print stirling(20,15)
# Output  =  452329200

#print stirling(30,10)

# End of Code

Note: When the values of n and k are large , it will take longer to calculate. For example, I have hashed out print stirling(30, 10) , as it can take a while to calculate. You can always unhash it and test how long it takes to calculate in your computer. Feel free to leave any comments or feedback.

Hope this helps. You can always subscribe to my blog to get more updates! Happy Coding!

ΞXΤЯ3МΞ

If you were wondering which is a good IDE for Python Development, there are a lot of them. My personal favorite is the Eclipse but I also use the default IDLE Python at times. This post is a guide on Installing and setting up Eclipse and PyDev in a Windows PC.

Pydev + Eclipse

Step 1: Install Python

You can find a guide on Installing Python in your system here.

Step 2: Install Eclipse

You can download the “Eclipse Classic” version (32-bit or 64-bit)  from http://www.eclipse.org/downloads/ (~ 184 Mb).

The downloaded file wil be a zip file. Simply extract it to any desired location,  For example, extract it to your C: drive. So, now your eclipse folder will be “C:\eclipse”.

To open up eclipse, go to your eclipse installation folder (It is “C:\eclipse” in mine) & open “eclipse.exe” .

eclipse folder

You would see the welcome splash screen and then , you would be prompted to “Select a workspace” . You can choose any location you want or just leave it to the default values.This will the location where your projects and source codes will be saved.

workspace launcher

Now, you will see the Eclipse Start Page. You click on the “x” marked in red to close it and go to to the Workplace.

eclipse home screen

Step 3: Install PyDev

In your Eclipse program, you need to check for updates. You can do so by clicking on the Help>Check For Updates from the toolbar.

After checking updates, install them if prompted. Then Click on Help>Install New Software.

Install new software

Now, you will be presented with  a screen as shown below. Click on “Add“.

Now , put  Name field as “PyDev” and “http://pydev.org/updates” as the Location and press “OK“.

add repo url

Now, wait for a few seconds while it processes it. Now, tick on PyDev as shown below and click “Next“.

tick pydev

Click “Next“.

Now, “Accept” the license agreement and click “Finish“. It would start downloading the necessary files and install PyDev. You will be prompted with a message box asking whether you Trust Certificates.,simply select them and press “OK“.

Installing pyDev
After the installation is complete,it will prompt you to restart Eclipse. So, you have now successfully installed PyDev in Eclipse.

Step 3: Configure Interpreter

Click on Window>Preferences

Preferences

Now click on “PyDev” to expand section and click on “Interpreter – Python“. Now, click on “Add“.

Now, add the Interpreter Name as “Python27” and “Interpreter Executable” as “C:\Python27\python.exe” . You can change the location if you installed python in another directory. Then press “OK“.

interpreter location

You will be prompted to make a selection of which folders to be added to the SYSTEM pythonpath. Simply, choose “Select All” and press “OK“.

Now, finally, you will have your preference windows similar to the one shown below:

Now, you have done configuring the Interpreter. Now, lets see how we can start coding python in Eclipse.

Step 4: Creating a sample Python project in Eclipse

To start a Python Project in Eclipse, Go to File>New>Project.

Creating New PyDev project in Eclipse

Now, select the Wizard as “PyDev Project” and click on “Next“.

Now, Put the Project Name as “Hello World” or anything you want. And select the option “Create ‘src’ folder and add it to PYTHONPATH“. And press on “Finish“. (You might be prompted if you want to open it with PyDev perspective, click Yes).

Creating Hellow World in Eclipse with pydev

Now, click on the small triangle indicated next to your “Project Name” to expand  it. Now, left click on “src” and select “PyDev Module“.

Now, choose any name (which is going to be the name of your python source file) and input it in the “Name” field and press “Finish”. Make sure that you DO NOT ADD the .py extension, you only need to add a name.

You may have to double click on the helloworld.py (or what you named it) to open the source code file.

Add the following line to the source code:

print “Hello World”

Save the file, by pressing CTRL+S or File>Save.

Python Source Editor

To run your python code, click on the button which looks like a small Green Play button, and Go to Run As>Python Run. 

running your python program

The output of your program will mostly be displayed in the lower portion of the Eclipse window as shown below.

Your python program output window

So, yeah you installed Eclipse, installed and configured PyDev and got a little familiar with writing python code and executing them in Eclipse. Thats all for today.

If you liked/disliked or have any sort of questions, please leave a comment. And yeah, you can always follow my blog to  get future updates. 😀

ΞXΤЯ3МΞ

You can download Microsoft Visual Studio 2012 Express Offline Installer from the Microsoft website. Or you can download it using the link below.

Download Link : Visual Studio Express 2012 Offline Installer (~608 MB)

It is an ISO image file, you can install it easily either by burning the ISO to a CD/DVD or simply by mounting the ISO using “DEAMON Tools Lite” . It can be downloaded from here.“Mount” the ISO file you downloaded using the DEAMON Tools Lite and run the “wdexpress_full.exe“.

Screenshots:

Install screen

Installation Progress:

Installation progress

Successful Complete Installation:

Completed Installation

Visual Studio 2012 Start page :

Visual Studio 2012 start page

 

ΞXΤЯ3МΞ

You can download Microsoft Visual Studio 2010 Express Offline Installer from the Microsoft website. Or you can download it using the link below.

Download Link : Visual Studio 2010 Offline Installer (~694 MB)

It is an ISO image file, you can install it easily either by burning the ISO to a CD/DVD or simply by mounting the ISO using “DEAMON Tools Lite” . It can be downloaded from here.  “Mount” the ISO file you downloaded using the deamon tools and run the “Setup.exe“.

Screenshot

The setup is simple and self explanatory. I have currently installed Visual C# 2010 Express in my system to work on some C# projects.

ΞXΤЯ3МΞ

Hey guys, been reading OpenCV for python and thought of posting a tutorial on Programming a Grayscale Image Convertor. I encourage you to google them , there are lots and lots of examples and code snippets. This is on how to a convert any image to gray scale using Python and OpenCV.

A sample input image and output image are shown below (YEah, I am big Iron Man Fan! :B). You can click on image to enlarge:

I have placed an image named “ironman.png” in the current working directory (i.e. I have the original image in the same directory as the  place where I have saved my Python code).

First we import the cv2 module:

import cv2

Then ,read the image to a variable named “image” :

image = cv2.imread('ironman.png')

Now, to convert to gray-scale image and store it to another variable named “gray_image” use the function cv2.cvtColor() with parameters as  the “image” variable and  “cv2.COLOR_BGR2GRAY” :

gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

So, now the variable “gray_image” will hold the gray-scale version of the input image.

Now, to write/save the converted gray-scale image to the hard disk, we use the function “cv2.imwrite()” with parameters as “the name of converted image” and the variable “gray_image” to which the converted image was stored:

cv2.imwrite('gray_image.png',gray_image)

So, now if you open the directory where you saved your python code, you can see a new image there : gray_image.png! Wow! 😀

Now, to display the original and the gray-scale ,we use function “cv2.imshow()” with parameters as the “window title” and the “image variable” :

cv2.imshow('color_image',image)             
cv2.imshow('gray_image',gray_image) 

Complete Code for GrayScale Image convertor:

# GrayScale Image Convertor
# https://extr3metech.wordpress.com

import cv2
image = cv2.imread('ironman.png')
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imwrite('gray_image.png',gray_image)
cv2.imshow('color_image',image)
cv2.imshow('gray_image',gray_image) 
cv2.waitKey(0)                 # Waits forever for user to press any key
cv2.destroyAllWindows()        # Closes displayed windows

#End of Code

 
Hope you enjoyed this post, feel free to comment and don’t forget to follow my blog! 😀
 
ΞXΤЯ3МΞ

OpenCV (Open Source Computer Vision) is a library of programming functions for real time computer vision. I just finished installing OpenCV 2.4.1  in ma laptop. It look a while for me to download as my internet connection was laggy for a while.

Step 1: Download and Install Python:

Firstly, you will need Python installed in your system. If you can download it from here and follow the instructions which I have written to get Python successfully running in your computer in my previous blog entry here. Python will be installed in default folder “C:\Python27\

Step 2: Download Numpy:

Then you will need to download Numpy and install it .

Download Link for Numpy: Numpy

It will find the default Python Folder and you can just install it will the default settings.

Step 3: Download OpenCV:

Download Link for OpenCV : OpenCV

Now double-click OpenCV.exe. When it asks for extraction folder just give it as C:\ . The files will be now be extracted to C:\opencv .This might take a while.

Now, open folder “C:\opencv\build\python\2.7” and copy all the files in that folder to the folder “C:\Python27\Lib\site-packages” .

Step 4: Test it!

Open up your Python IDLE by clicking Start>All Programs>Python 2.7> IDLE (Python GUI) and type:

import cv2

If you have followed the described steps , then it would successfully import it and you can start programming right away! 😀

The OpenCV documentation can be found here.

ΞXΤЯ3МΞ

Cleaning the Prefetch folder in Windows OS helps increasing the performance of the system. You can clean your Prefetch files manually by going to the X:\Windows\Prefetch\ folder and deleting all the files in that directory. This can be time consuming and today I will be introducing the “os” module in python and show you how to create your own prefetch cleaner program so that you clean the prefetch folder for you in a single click.

So, basically the prefetch cleaner simply changes the current directory to your Prefetch folder(X:\Windows\Prefetch\ , where X is your drive where your Windows is installed) and gets the list of files in that folder and deletes each one of them.

Assuming you have python installed in your computer(else read my other blog post on how to install python here). Now, import the “osmodule using the following code:

import os

The next thing you need to do is to change your current working directory to the prefetch directory. This can be done using the function called “chdir(path)” in the os module. The parameter path is going to be the prefetch directory which in my case is “C:\WINDOWS\Prefetch“. So, we we use the following line of code:

os.chdir("C:\WINDOWS\Prefetch")

Now, you need to get the list of all the files in that directory .This can be done using the function listdir(path) which returns a list containing the list of files in that directory and storing the result to a variable( For example: prefetch):

prefetch=os.listdir("C:\WINDOWS\Prefetch")

Now, since we have the list of files,  to delete each file in the list you can simply use a for loop to traverse through each element in the list and call a function that deletes the file.  Now, we create a function called del_file(name) which takes takes a “filename” as parameter and deletes the file. We can delete a file using the function os.remove(filename) . The function can be implemented as:

def del_file(name):
    os.remove(i)
    print i, " Deleted"

Now, finally you need to just create a for loop to traverse through all the elements(which are filenames of each file in the directory) in the variable prefetch and call the function del_file(i).

for i in prefetch:
    del_file(i)

Complete source code of the Prefetch Cleaner:

# Prefetch Cleaner
# https://extr3metech.wordpress.com
import os

def del_file(name):
    os.remove(i)
    print i, " Deleted"

os.chdir("C:\WINDOWS\Prefetch")
prefetch=os.listdir("C:\WINDOWS\Prefetch") # Change letter "C" to your OS drive letter

for i in prefetch:
    del_file(i)

print "Prefetch Cleaning Complete "
raw_input("Press Enter to exit..")

It is recommended that you close all media players such as VLC or Windows Media Player etc before you run your prefetech cleaner program. Happy Coding!

ΞXΤЯ3МΞ