Browsing Tag

learn programming

Classes

10 Lessons Needed To Learn Programming In Any Language*

October 19, 2015

Without farther delay, here is my top 10 lessons to learn programming in the order they should be taught:

  1. Environment Setup, Input/Output
  2. Integers and basic arithmetic (+,-,*,/,%) + order of operations ()
  3. Float Arithmetic
  4. Variables
  5. Booleans
  6. Conditional Statements & Control Structures
  7. Functions
  8. Strings & Arrays
  9. Classes
  10. Exceptions

Ok, I lied. A lot of these have to be broken down and cross referenced. However, I think that should be the order in which people are introduced to programming. Too often people try to learn everything all at once. You can’t learn how to swim by jumping into the deep end. Well, some of us can. Learning a new skill isn’t always as easy to other people as it was to the teacher. Whenever I get a chance to be a bookstore, I like to look at beginner programming books. They all promise to teach a lot in a very short time. The honest truth is there is no shortcut. It takes a couple of years of programming in order to become a half dissent programmer. It is not because it is hard, it is just because there are too many variables. There are so many different things that you need to learn, that it can’t occupy just one book. It can’t even occupy the whole Internet. New things come up everyday that change what you knew before. Becoming a programmer is just one of these thing that require time.

So what is with this list? I got asked too many times at this point how I started programming and where/how to start. I have decided to write my own intro to programming. Over the next weeks I will publish small lessons that will build up to an ebook on programming. I will use Python-ish style code and most of the content will be generalized for almost any language. By the end of the book, you will be able to learn the syntax to a new language and program in any language you want. Best of all, the ebook and lessons will all be posted on this site and will be FREE. No strings attached. I believe anyone can learn programming at any age and that education should be available to all.

I have taught a few students before and there are several reasons why my list is different from other learn programming classes. The main objective is to start with something familiar that everyone in the 5th grade should know. Basic arithmetic and numbers. Than slowly build up while introducing new ideas and concepts. The secondary objective is to fully learn a topic before moving forward. That means when we will talk about a new concept we will go back and see how it reflects on other topics we have learned before. We are going to aim to turn fragile knowledge into concrete building blocks that will help us move forward and ultimately complete our objectives.

It should be mentioned what this course will not achieve. Beyond all else, you will not become a certified programmer or a hacker. Like I said before, that will take time. There is no class in the universe that can teach time. After you have completed the lessons, you will have to continuously learn new skills and develop yourself as a programmer. Think about learning programming more like going to the gym. You will not get a six pack and lose 50 lbs. in one setting, it takes time. Same thing with programming. You need to invest time to become a programmer. Just like going to the gym everyday, it will pay off in the long run and you future self will look back and thank you.

There are a bunch of reasons of why you should learn programming, I don’t feel like repeating most of them. I will just mention one. Programming is everywhere and it is here to stay. Programming has become a tool that used in virtually every field, even philosophy and history. Programming is almost equivalent to using excel. It is a skill more and more employers are looking for and will make you more valuable and your job easier. There are endless examples of how programming can shorten your job and sometimes turn an impossible human task into a simple short snippet of code. I believe that if you are reading up until this point, you already have a goal to learn programming. Or maybe you have already been through a class, but feel like you have missed the points and you want to know more. In programming there is always more to learn. Remember that.

First lesson will be published within a week. Make sure to follow me on Twitter @CptDeadBones to get notified.

* Ok. So technical, the class will teach you how to program in almost any language.

Computer Programming I, Java, Programming Languages

The Rainfall Problem in Java

March 28, 2014

It has been quite a while since I have posted any code in Java. As I was going through some Java questioners, I came across the Rainfall problem. The rainfall problem in java is quite simple, the user is going to enter data, the average participation per day r something, and the output is some statistical information. To keep things interesting, no arrays can be used, so everything needs to be computed on the fly. For our purpose, the user will enter the last 12 months data, an he output will be the minimum, maximum and average participation. This is fairly simple and a great exam or interview question.

Note that the code will check that enteries are non negative numbers.

Here is how this is going to look in Java:

import java.util.Scanner;

public class Rainfall {

 public static void main(String[] args) {

  //variable setup
  Scanner input = new Scanner(System.in);
  String userInput = "";
  double sum = 0.0;
  final int COUNT = 12;
  boolean valid = true;

  //initiazlize variables min and max to something out of range
  double min = 999999999999.9;
  double max = -0.1;
  int min_month = 0;
  int max_month = 0;

  //temp variable
  double curr = 0.0;

  for (int i=0; i < COUNT; i++){

    //user input validation
    do{

		//get user input
        System.out.print("enter the rainfall for month number " + (i+1) +": ");
        userInput=input.nextLine();

		try{

			//convert input to double
			curr = Double.parseDouble(userInput);
			valid = true;

			//throw error if input is less than 0
			if(curr < 0) throw new Exception();

		} catch (Exception e) {

			System.err.println("\nThat was not a valid entry! \nPlease try again.\n");
			valid = false;
									}
   } while (!valid);

   //keep a running total
   sum+= curr;

   //find min
   if(curr < min){
     min = curr;
     min_month = i+1;
   }

   //find max
   if(curr > max){
     max = curr;
     max_month = i+1;
   }

  } //end for loop

  //compute the average
  double avg = sum/COUNT;

  //report the result
  System.out.println("\nThe avg rainfall is " + String.format("%.2f", avg) +
    "\n" + "The min rainfall is " + min + " for month number " + min_month +
    "\n" + "The max rainfall is " + max + " for month number " + max_month );
 }
}

Here is how the output should look like:

wpid-rainfall_output-2014-03-24-03-24.png

Cool Stuff, Programming Languages, Python

The Game of Battleships in Python

February 17, 2014

A couple of weeks ago we talked about the game of Tic Tac Toe. I thought it would be fit to talk about another game, Battleships. Both games are excellent beginner games for programming and Python makes it very easy to implement them without a lot of hassle. You will notice that this article is a little different from my regular work. Normally I have the output of the function embedded. Since this is a game, like Tic Tac Toe, it is hard to capture the game in a single screen shoot. I will have some screen shoots toward the end of the article when I talk about printing out the board. Before we begin let us lay some ground rules for the game:

  1. This is a modified version of the game Battleships.
  2. The coordinates used for this game are all numeric.
  3. The game will be played against a random computer player.
  4. The computer will place random ships that are hidden from the user.
  5. The turns alternate between player regards of hit or miss.

Let us begin by laying out our main logic for the game. Here is some pseudo code that will help keep us inline:

  1. Setup the boards for both computer and user
  2. Place ships
  3. Alternate turns asking for coordinates and check win condition.

That is just a very rough outline. Of course the game itself is a lot more complex than this. So let’s get started. First we need to think about data representation. We need to have 2 boards that are 10 X 10. That is easy, it is just a list of lists with 10 lists. We will say that a cell is empty if it contains a “-1” value. So we just need to initiate this list of lists like this:


#setup blank 10x10 board
	board = []
	for i in range(10):
		board_row = []
		for j in range(10):
			board_row.append(-1)
		board.append(board_row)

	#setup user and computer boards
	user_board = copy.deepcopy(board)
	comp_board = copy.deepcopy(board)

Notice that we had to use the Python copy module to make sure we are not pointing to the same memory. There are other ways to this, like having the code duplicated. This is a topic for another day, in the mean time, here is a nice article about Deep and Shallow copies in Python. You may want to note that some of this principles are actually global and have parallels in other languages. So we have the boards, but what about this ships? Well, that is easy, what if we have a dictionaries attached to our list of list as the final element. The dictionary will look like this:


ships = {"Aircraft Carrier":5,
		     "Battleship":4,
 		     "Submarine":3,
		     "Destroyer":3,
		     "Patrol Boat":2}

Ok. So we have the easy part taken away. Now we have to look at how to place the ships. That is a little more complex. Lets first think about our logic. We need to figure out first that the coordinates entered by the user are valid. Then we have to ask orientation of the ship. After that we need to make sure that a ship can be actually placed. For example, what if we are trying to place a Patrol Boat at row: 10 col: 8, vertically? We cannot place the ship there. Horizontally we can, but that is another entry. So we will need to validate the request. If all is good, we will use the first letter of the ship name as a place holder on the board. Seeing the code might hep a little, so here it is:


def user_place_ships(board,ships):

	for ship in ships.keys():

		#get coordinates from user and vlidate the postion
		valid = False
		while(not valid):

			print_board("u",board)
			print "Placing a/an " + ship
			x,y = get_coor()
			ori = v_or_h()
			valid = validate(board,ships[ship],x,y,ori)
			if not valid:
				print "Cannot place a ship there.\nPlease take a look at the board and try again."
				raw_input("Hit ENTER to continue")

		#place the ship
		board = place_ship(board,ships[ship],ship[0],ori,x,y)
		print_board("u",board)

	raw_input("Done placing user ships. Hit ENTER to continue")
	return board

You will notice that we call 5 functions we did not talk about yet. So let us talk about them. We will talk about the printing function in a little bit. We will take a look first at the get_coor() function. Before you get cold feet I do warn you that this function is lengthy. Keep in mind that the function accounts for user errors and will make sure that the only input it will accept and return is 2 values that are between 1 - 10. Nothing more, nothing less.


def get_coor():

	while (True):
		user_input = raw_input("Please enter coordinates (row,col) ? ")
		try:
			#see that user entered 2 values seprated by comma
			coor = user_input.split(",")
			if len(coor) != 2:
				raise Exception("Invalid entry, too few/many coordinates.");

			#check that 2 values are integers
			coor[0] = int(coor[0])-1
			coor[1] = int(coor[1])-1

			#check that values of integers are between 1 and 10 for both coordinates
			if coor[0] > 9 or coor[0] < 0 or coor[1] > 9 or coor[1] < 0:
				raise Exception("Invalid entry. Please use values between 1 to 10 only.")

			#if everything is ok, return coordinates
			return coor

		except ValueError:
			print "Invalid entry. Please enter only numeric values for coordinates"
		except Exception as e:
			print e

Ok. So that was a mouth full. How about the next one, the v_or_h()? That is a little more straight forward, it only return V or H. This should be simple:


def v_or_h():

	#get ship orientation from user
	while(True):
		user_input = raw_input("vertical or horizontal (v,h) ? ")
		if user_input == "v" or user_input == "h":
			return user_input
		else:
			print "Invalid input. Please only enter v or h"

Recall that we are doing all this to place the user ships. So at this point we have a valid coordinate from the user and an orientation. Now we go back to our placement issue. We need to make sue that the type of ship can be placed where the user wants it. To do this we just need to check that it can physically be placed within the board limits and that the cells are empty (-1).


def validate(board,ship,x,y,ori):

	#validate the ship can be placed at given coordinates
	if ori == "v" and x+ship > 10:
		return False
	elif ori == "h" and y+ship > 10:
		return False
	else:
		if ori == "v":
			for i in range(ship):
				if board[x+i][y] != -1:
					return False
		elif ori == "h":
			for i in range(ship):
				if board[x][y+i] != -1:
					return False

You should note that this function returns a boolean value of True or False. This is so we can use it when we write the computer version of place ships, we can use the validate() function without writing a new one. Now all we have look at, excluding the print function is the actual placement of the ships. Recall that all we need to do at this point is put the intial character of the ships name.


def place_ship(board,ship,s,ori,x,y):

	#place ship based on orientation
	if ori == "v":
		for i in range(ship):
			board[x+i][y] = s
	elif ori == "h":
		for i in range(ship):
			board[x][y+i] = s

	return board

You will notice that this looks very much like a function that we can reuse, just like the validate() function. Perhaps now is a good time to look at the ship placement for the computer agent.


def computer_place_ships(board,ships):

	for ship in ships.keys():

		#genreate random coordinates and vlidate the postion
		valid = False
		while(not valid):

			x = random.randint(1,10)-1
			y = random.randint(1,10)-1
			o = random.randint(0,1)
			if o == 0:
				ori = "v"
			else:
				ori = "h"
			valid = validate(board,ships[ship],x,y,ori)

		#place the ship
		print "Computer placing a/an " + ship
		board = place_ship(board,ships[ship],ship[0],ori,x,y)

	return board

The main difference between the user and computer ship placement is that the computer uses randomization to place the ships while the user enters the information. At this point we have our setup complete and can play the game. The 2 functions that will handle the game are user_move and computer_move. Let us take a look at both:


def user_move(board):

	#get coordinates from the user and try to make move
	#if move is a hit, check ship sunk and win condition
	while(True):
		x,y = get_coor()
		res = make_move(board,x,y)
		if res == "hit":
			print "Hit at " + str(x+1) + "," + str(y+1)
			check_sink(board,x,y)
			board[x][y] = '$'
			if check_win(board):
				return "WIN"
		elif res == "miss":
			print "Sorry, " + str(x+1) + "," + str(y+1) + " is a miss."
			board[x][y] = "*"
		elif res == "try again":
			print "Sorry, that coordinate was already hit. Please try again"

		if res != "try again":
			return board

def computer_move(board):

	#generate user coordinates from the user and try to make move
	#if move is a hit, check ship sunk and win condition
	while(True):
		x = random.randint(1,10)-1
		y = random.randint(1,10)-1
		res = make_move(board,x,y)
		if res == "hit":
			print "Hit at " + str(x+1) + "," + str(y+1)
			check_sink(board,x,y)
			board[x][y] = '$'
			if check_win(board):
				return "WIN"
		elif res == "miss":
			print "Sorry, " + str(x+1) + "," + str(y+1) + " is a miss."
			board[x][y] = "*"

		if res != "try again":

			return board

Fist thing you will notice is the infomus function get_coor(). We have used it before and it will work for us again. Now we have 3 more function we need to look at in order to understand how this works. We will start with make_move() this function looks like this:


def make_move(board,x,y):

	#make a move on the board and return the result, hit, miss or try again for repeat hit
	if board[x][y] == -1:
		return "miss"
	elif board[x][y] == '*' or board[x][y] == '$':
		return "try again"
	else:
		return "hit"

All this function really does is looks at the board in a particular cell and returns a value at that cell. Based of the result the board will be updated if needed. Now we need to check if a ship got sunk. This is easy. If you recall we have a dictionary containing the ships and the amount of hits they can take. This is the last element in the board data representation. So this is not as bad as you might think. We just need to figure out what ship got hit and if it has more damage points.


def check_sink(board,x,y):

	#figure out what ship was hit
	if board[x][y] == "A":
		ship = "Aircraft Carrier"
	elif board[x][y] == "B":
		ship = "Battleship"
	elif board[x][y] == "S":
		ship = "Submarine"
	elif board[x][y] == "D":
		ship = "Destroyer"
	elif board[x][y] == "P":
		ship = "Patrol Boat"

	#mark cell as hit and check if sunk
	board[-1][ship] -= 1
	if board[-1][ship] == 0:
		print ship + " Sunk"

Cool. Now for the last function, check_win(). Now this can be done better, but I was tired at this point so I went for simple. If you think about it, a board is in a win condition if all the ships are gone. That means that in our representation, all the cells must conation a -1 for empty, a $ for a hit or a * for a miss. Any other character is a ship and there fore not a win. So the function can look like this:


def check_win(board):

	#simple for loop to check all cells in 2d board
	#if any cell contains a char that is not a hit or a miss return false
	for i in range(10):
		for j in range(10):
			if board[i][j] != -1 and board[i][j] != '*' and board[i][j] != '$':
				return False
	return True

So now we have our puzzle almost complete. The last pice we need is a good print function. This function is built upon the Tic Tac Toe function, but is a little more complex. Recall that there are 2 printing functions that we need. When the users sees the computer board, the ships should be hidden. However, when the user is presented with their own board, they should see all the ships. In wither case, the hits and misses should be displayed and the ‘-1’ should not be printed. This took me a while to get working properly. Mostly because I wanted it to look good, for me. Here is the printing function:


def print_board(s,board):

	# WARNING: This function was crafted with a lot of attention. Please be aware that any
	#          modifications to this function will result in a poor output of the board
	#          layout. You have been warn.

	#find out if you are printing the computer or user board
	player = "Computer"
	if s == "u":
		player = "User"

	print "The " + player + "'s board look like this: \n"

	#print the horizontal numbers
	print " ",
	for i in range(10):
		print "  " + str(i+1) + "  ",
	print "\n"

	for i in range(10):

		#print the vertical line number
		if i != 9:
			print str(i+1) + "  ",
		else:
			print str(i+1) + " ",

		#print the board values, and cell dividers
		for j in range(10):
			if board[i][j] == -1:
				print ' ',
			elif s == "u":
				print board[i][j],
			elif s == "c":
				if board[i][j] == "*" or board[i][j] == "$":
					print board[i][j],
				else:
					print " ",

			if j != 9:
				print " | ",
		print

		#print a horizontal line
		if i != 9:
			print "   ----------------------------------------------------------"
		else:
			print

So to sum it all up, here is a link to the complete code Battleships in Python Command Line. Here are some screen shoots I took from the game play:

wpid-python_battleships_placing_ships-2014-02-16-19-17.png

wpid-python_battleships_user_ships-2014-02-16-19-17.png
wpid-python_battleships_computer_placing_ships-2014-02-16-19-17.png

wpid-python_battleships_user_move-2014-02-16-19-17.png

wpid-python_battleships_computer_hitship-2014-02-16-19-17.png

wpid-python_battleships_user_move-2014-02-16-19-17.png
wpid-python_battleships_userwon-2014-02-16-19-17.png

Have Fun!

Cool Stuff, Programming Languages, Python

Sending Email From Python Using Command Line

January 10, 2014

Since many of my commenters ask for something a little more advance in Python, I wrote up this script I wrote. Notice that this script will allow you to use almost anything you would come to except from an email client. Sending Email From Python is simpler than you think. That includes cc and bcc fields, html mode and attachment files. You will have to use your own email configuration, I left the settings from gmail, but any email account could be used. Just fill in your user name and password. You can include this module and use the compose_email() function to send emails directly from you Python program. As a word of advice, try to not send too many emails all at once (like 400 emails). Gmail will not send the emails and your email address will be marked as spam. Use with caution.

NOTE: The only output of the program is a single print statement (assuming it all went well), that will indicate an email has been sent.


#account setup
username = '***';
password = '***';
server = 'smtp.gmail.com:587';

#imports
from time import sleep;
import smtplib;
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText;
from email.mime.multipart import MIMEMultipart;

# create msg - MIME* object
# takes addresses to, from cc and a subject
# returns the MIME* object
def create_msg(to_address,
               from_address='',
               cc_address='',
               bcc_address='',
               subject=''):

    msg = MIMEMultipart();
    msg['Subject'] = subject;
    msg['To'] = to_address;
    msg['Cc'] = cc_address;
    msg['From'] = from_address;
    return msg;

# send an email
# takes an smtp address, user name, password and MIME* object
# if mode = 0 sends to and cc
# if mode = 1 sends to bcc
def send_email(smtp_address, usr, password, msg, mode):
    server = smtplib.SMTP(smtp_address);
    server.ehlo();
    server.starttls();
    server.ehlo();
    server.login(username,password);
    if (mode == 0 and msg['To'] != ''):
        server.sendmail(msg['From'],(msg['To']+msg['Cc']).split(","), msg.as_string());
    elif (mode == 1 and msg['Bcc'] != ''):
        server.sendmail(msg['From'],msg['Bcc'].split(","),msg.as_string());
    elif (mode != 0 and mode != 1):
        print 'error in send mail bcc'; print 'email cancled'; exit();
    server.quit();

# compose email
# takes all the details for an email and sends it
# address format: list, [0] - to
#                       [1] - cc
#                       [2] - bcc
# subject format: string
# body format: list of pairs [0] - text
#                            [1] - type:
#                                        0 - plain
#                                        1 - html
# files is list of strings
def compose_email(addresses, subject, body, files):

    # addresses
    to_address = addresses[0];
    cc_address = addresses[1];
    bcc_address = addresses[2];

    # create a message
    msg = create_msg(to_address, cc_address=cc_address , subject=subject);

    # add text
    for text in body:
        attach_text(msg, text[0], text[1]);

    # add files
    if (files != ''):
        file_list = files.split(',');
        for afile in file_list:
            attach_file(msg, afile);

    # send message
    send_email(server, username, password, msg, 0);

    # check for bcc
    if (bcc_address != ''):
        msg['Bcc'] = bcc_address;
        send_email(server, username, password, msg, 1);

    print 'email sent'

# attach text
# attaches a plain text or html text to a message
def attach_text(msg, atext, mode):
    part = MIMEText(atext, get_mode(mode));
    msg.attach(part);

# util function to get mode type
def get_mode(mode):
    if (mode == 0):
        mode = 'plain';
    elif (mode == 1):
        mode = 'html';
    else:
        print 'error in text kind'; print 'email cancled'; exit();
    return mode;

# attach file
# takes the message and a file name and attaches the file to the message
def attach_file(msg, afile):
    part = MIMEApplication(open(afile, "rb").read());
    part.add_header('Content-Disposition', 'attachment', filename=afile);
    msg.attach(part);

#to be tested...
compose_email(['cpt@thelivingpearl.com','',''],
              'test v.5.0',
              [['some text goes here...\n',0]],
              '');

#compose_email can take the following arguments:
#	1. to recipients (separated by a comma)
#	2. cc recipients (separated by a comma)
#	3. bcc recipients (separated by a comma)
#	4. subject
#	5. a list with message and mode (plain txt or html)
#	6. files to be attached

Programming Languages, Python

Temperature Conversion Application In Python

January 2, 2014

Last time we talked about using functions in Python, this time let us take it a step farther and create a module. Functions are great and you are going to use them everywhere, but what happens when you need to use a function in more than one place? What happens when a function needs to be utilized in different files within one application? In Python, we create modules, which are just your regular .py files. We can use functions (and objects) from other files by using an import statement. Every language has some form of an import statement. In C we use an include statement. The idea is that when you need, you can include code from another code file. For this post, lets assume a scenario. Imagine that you are an entry level programmer at a software company. You are assign to a team that is working on some large scale scientific application in Python. As the newbie on the team, you are giving the task to write functions that will be used for temperature conversation in multiple parts of the program. You are given the following function pseudocode and are requested to write the code for them:

  1. c2f(t) will take a float temperature in Celsius and return a float temperature in Fahrenheit
  2. c2k(t) will take a float temperature in Celsius and return a float temperature Kelvin
  3. f2c(t) will take a float temperature in Fahrenheit and return a float temperature Celsius
  4. f2k(t) will take a float temperature in Fahrenheit and return a float temperature Kelvin
  5. k2c(t) will take a float temperature in Kelvin and return a float temperature in Celsius
  6. k2f(t) will take a float temperature in Kelvin and return a float temperature in Fahrenheit

So these functions are pretty easy to write, they are all 1 line of code. Using some basic formulas from Wikipedia Conversion of units of temperature the code in Python for temperature conversion might look like this:


def c2f(t):
	return (t*9/5.0)+32

def c2k(t):
	return t+273.15

def f2c(t):
	return (t-32)*5.0/9

def f2k(t):
	return (t+459.67)*5.0/9

def k2c(t):
	return t-273.15

def k2f(t):
	return (t*9/5.0)-459.67

That was simple. Notice that we have included in every calculation an implicate conversion to float, so even if t is not a float, the result will return as a float. That might be useful if at some other part of the application some numeric calculation is required. Especially if the calculation requires higher level of accuracy. Within a couple of minutes you hand your boss (email him/her) a file named temperature.py and you think you are done. In most cases you might be done, but have you tested your code? Rushing code is never a good idea. Take the time to fully test you code and make sure it works the way you think it does. This example might be straight forward, but other examples might be more complicated. It is a good habit to always self test you code. Here is one way you can test the code:


def main():

	menu = “\nTemperature Convertor\n\n"+\
	 	"1. Celsius to Fahrenheit\n"+\
		"2. Celsius to Kelvin\n"+\
		"3. Fahrenheit to Celsius\n"+\
		"4. Fahrenheit to Kelvin\n"+\
		"5. Kelvin to Celsius\n"+\
    		"6. Kelvin to Fahrenheit\n"+\
		"7. Quit"

	user_input = 0
	while user_input != 7:
		print menu
		user_input = raw_input("Please enter a valid selection: ")

		try:
			user_input = int(user_input)
		except:
			print user_input + " is not a valid selection, please try again\n"

		if user_input == 1:
			t = get_user_input()
			print str(t) + " degree Celsius is " + str((c2f(t))) + " degree Fahrenheit"
		elif user_input == 2:
			t = get_user_input()
			print str(t) + " degree Celsius is " + str((c2k(t))) + " degree Kelvin"
		elif user_input == 3:
			t = get_user_input()
			print str(t) + " degree Fahrenheit is " + str((f2c(t))) + " degree Celsius"
		elif user_input == 4:
			t = get_user_input()
			print str(t) + " degree Fahrenheit is " + str((f2K(t))) + " degree Kelvin"
		elif user_input == 5:
			t = get_user_input()
			print str(t) + " degree Kelvin is " + str((k2c(t))) + " degree Celsius"
		elif user_input == 6:
			t = get_user_input()
			print str(t) + " degree Kelvin is " + str((k2f(t))) + " degree Fahrenheit"
		elif user_input == 7:
			quit()
		else:
			print str(user_input) + " is not a valid selection, please try again\n"

if __name__ == "__main__":
	main()

The output of the code might look like this: wpid-python_tempeature_converstion-2014-01-2-19-29.png Now this main() function is in a different file called converter.py. The file content has now functions that can convert anything. However, in the very top of the file there is one magical statement:


from temperature import *

There are different ways to include code from another .py file, but for now, we can use this one. All it is is a small indication for Python to know that if they need to open a temperature.py file as well as the converter.py file. The only requirement is that both files are in the same working directory, that is that they are in the same folder. When you examine the code you may notice that some code was added to account for invalid entries, such as if a user enters a character instead of a number. There is also a hidden function called get_user_input() that looks like this:


def get_user_input():

	user_input = 0
	while type(user_input) != type(1.0):
		user_input = raw_input("Enter degrees to convert: ")
		try:
			user_input = float(user_input)
		except:
			print user_input + " is not a valid entry"
	return user_input

This function makes sure the user enters a numeric value to convert. At this point you have all the tools necessary to tell you boss that you have tested you code and it works properly. You might also want to keep this as part of the code in case you want to use it in the future. I have uploaded the code in case you want to test it out for yourself, Temperature Conversation Application in Python.

Programming Languages, Python

Introduction to Functions in Python

December 23, 2013

As you begin to learn programming, sooner or later you will run into the issue of rewriting code. That is one of the many reasons we teach and learn to write functions. Functions are much like the mathematical equivalent, they are machines, with some input and output. Somewhere in school you might have learned that a function f takes a value x and has an output y. Much like that we have functions in programming that can take variables or arguments and have an output of some result. The inner working of a function in math is more technical, like f(x) = 2x + 3. In a similar matter, functions in programming execute statements.

500px-Function_machine2.svg

There are 4 different types of functions that we can consider:

  1. No variables and no return
  2. Variable and no return
  3. No variable and a return
  4. Variable and return

Let us look at some examples. First let us look at the syntax requirements by Python to write Functions in Python. Like before, we will consider Python 2.7 to be our standard. The same ideas will apply to other versions and even other languages. You can take a look at the Python 2.7 function definition for more reading, but the basic definition of a function in python will look something like this:

def <function_name>(<Variables>) :
    <body>

Where <function_name> is a must, <Variables> are optional and <body> can be as minimal as pass. So what is our most minimal function? The useless function:


def useless():
	pass

As you may guess, using this function is pointless, but that brings up another question, how do we use functions? That is simple, we call functions, by name. So if we were to make use of this function we can call it by the statement:


useless()

Now this is pointless, since nothing will let you know that the function even executed correctly. Computers today are so fast, in a blink of an eye your program will run through the code, and without any output, there is nothing to make the user verify that something actually happened. This brings us to the first kind of functions, functions without variables and without a return. You may think this is pointless by itself, but let’s say you need to do a menu to allow the user to select from 3 options, something that looks like this:

wpid-pyhton_basic_menu-2013-12-23-10-21.png

The beginning code can look something like this:


print "1. do something"
print "2. do something else"
print "3. quit"

user_input = raw_input("Please make a valid selection: ")

if user_input == "1":
	print "doing something..."

elif user_input == "2":
	print "doing something else"

elif user_input == "3":
	quit()

else:
	print "not a valid selection" 

Now this is nice, but what if we have to repeat this, won’t it be easier in a loop. Sure it will! To change it we will need to add a while statement and set user_input to some initial value. Our code will look now like this:


user_input = 1

while user_input != 3:

	print "1. do something"
	print "2. do something else"
	print "3. quit"

	user_input = raw_input("Please make a valid selection: ")

	if user_input == "1":
		print "doing something..."

	elif user_input == "2":
		print "doing something else"

	elif user_input == "3":
		quit()

	else:
		print "not a valid selection" 

Now that is a little more intuitive. Now our program will execute code, but keep going back to the main loop. It would be helpful if instead of the print statements, we change it to have a single function call, to out function that takes no variables and has no return. That is right, a useless function is perfect for printing out information.


def print_menu():

	print "1. do something"
	print "2. do something else"
	print "3. quit"

You may some other usage for a function of such. I normally use them for printing out user information, such as help instructions and menus. You might find other use to them, such as updating global variables, but that is beyond the scope of this post. Let us look at our code now inside the while loop:


print_menu()

user_input = raw_input("Please make a valid selection: ")

if user_input == "1":
	print "doing something..."

elif user_input == "2":
	print "doing something else"

elif user_input == "3":
	quit()

else:
	print "not a valid selection" 

The next type of functions we want to examine are those who take a variable and return now value. Let’s say we want a function that will print out “ho” a given number of times. a function like that might look like this:


def ho(n):
	for i in range(n):
		print "ho",
	print

Notice that the function is named ho, and that it has a variable name in the parentheses. The variable will receive a value when we call the function. If no value is given, we will get a trace back that looks like this:

wpid-python_functions_errors_1-2013-12-23-10-21.png

We want to try to avoid that. To do so, we can assign a defualt value, just in case we “forget” to give it a value. We do this by adding an equal sign and a value. Like this:


def ho(n=3):
	for i in range(n):
		print "ho",
	print

So now we can call this function by ethier just the name, or by giving it a number of time to print “ho”. Like this:


ho()

ho(5)

The output will be:

wpid-python_ho_function_output-2013-12-23-10-21.png

These types of functions are useful for all sort of things. usually, things that can be computed or executed without any of the results needing to come back to our main program. Let us look at another example that has more than 1 variable, the power function. Let us say that the default value of the power is always 2, but the base has to be given by the user. The result does not need to be stored, it can be printed out to the screen. This function might look like this:


def power(base,exp=2):
	print base ** exp

Notice that we have multiple variables, 1 with no default value and 1 with a default value. In theory, a function can has as many variables as you need. It may also have a dynamic number of variables. As a rule of thumb, if you have over 4-5 variables as arguments for your function, you may want to rethink your logic a little. Let us look at the output of our power function and some function calls:


power(2)

power(5)

power(5,3)

wpid-python_power_function_output-2013-12-23-10-21.png

You may think that this is it, but it is not. Until now we say functions that do something and output to the screen something. What if we actually need the value? What if we are within a bigger program and we need the value of the power function? We will get back to that in a minute. Let us first talk about function with no variables. Such function are getters of values, something like a random number generator. Lets say we need a function that will return 2 every time it is called. I know, it seems pointless, but it is for demonstration only. That function will look like this:

def rtn_2():
    return 2

Notice that we use a special reserved keyword return. The values, or variables, after that word is what the function returns. In this case we return the value 2. Now, our function call is the same, but since we return a value, that normally means we want to store it somewhere. So out function call changes from just the name of a function to a variable assignment statements that looks like this:

value = rtn_2()

The value returned from the function rtn_2 will be stored in the variable value for future usage. We can also have multiple return statements and multiple values returns, but that is another topic by itself. Now we are ready to talk about the most common and most useful function type, functions with variables and return types. Let us say that we want to modify our power function from before to return the value, we can modify it to look something like this:


def power2(base,exp=2):
	return base ** exp

That was easy. Now the value computed will be returned tot he calling function for future reference. Cool. Lets see if we can combine all 4 functions to be call from our menu program (Again, just inside the while loop):


print_menu()

user_input = raw_input("Please make a valid selection: ")
print

if user_input == "1":
	n = input("enter a number: ")
	ho(n)

elif user_input == "2":
	base = input("enter a number: ")
	print str(base) + " to the power of 2 is ",
	power(base)
	base = input("enter a number: ")
	exp = input("enter a number: ")
	print str(base) + " to the power of " + str(exp) + " is ",
	power(base,exp)

elif user_input == "3":
	value = rtn_2()
	print "The value is " + str(value)

elif user_input == "4":
	base = input("enter a number: ")
	res = power2(base)
	print str(base) + " to the power of 2 is " + str(res)
	base = input("enter a number: ")
	exp = input("enter a number: ")
	res = power2(base,exp)
	print str(base) + " to the power of " + str(exp) +" is " + str(res)

elif user_input == "5":
	quit()

else:
	print "not a valid selection" 

print

The full python function example can be viewed here. Some notes about the program and functions in general:

  • First, you will notice some print statements, those were added for ease of use.
  • Second, the function we discussed here are mostly integer ones. That is not the only case for use of functions, variable can be of any Python data type.
  • Return type of function can be of any type. The ones we showed here are not the only one.
  • There is much more to say about functions, but I might leave that out for next time, this article is getting long enough as is.

So there you have it, a nice beginner introduction into the wonderful world of functions. As I mentioned not 2 lines ago, there are many others function techniques and things you can do with them. I might try to have a following post covering these aspect coming out soon.

Happy Holidays!

Computer Programming I, Programming Languages, Python

Compute the Average, Min, Max and Mode of a List in Python

October 24, 2013

Lists are by far the most common data type you will use in Python. I wanted to take a few minutes to see how easy Python make the use os lists. I also want you to notice how much ground we can cover by just thinking about these properties of a list. In this article we will talk about lists, functions, searching, return values, data tpes, diconaaries, try-catch try-except blocks and more interesting Python techniques.

So we will be finding the average, min, max and mode of a list. I won’t go into different theories on how to efficiently find these, but rather straight forward approach. Let us start by an assumption that all the values in our list are going to be integers and the data is already stored in a variable named list. As before, we will be using Python 2.7, here is a copy of Python2.7 documentation if you need it. Coming from that we can start by saying our main function looks like this:


def main():

	list = [3,4,1,20,102,3,5,67,39,28,10,1,4,34,1,6,107,99]

	avg(list)
	min(list)
	max(list)
	mode(list)

This will simply call 4 different functions that will each find and print what we are looking for. First, lets go over some list basic properites. In all these function we will use for loops to iterate over the elements of the array. Lucky Python has a simple syntax that allows us to have a variable in the for loop that will take the values of the array.

What does this mean? You will recall that arrays have 0 indexing property that allows us to access the elements in the array directly. If we were to have the syntax list[0] is our example, the value will correspond to 3. the syntax list[1] will have the value 4. We can access each element individually and directly. We can use this to change values in the array. If we were to have list[0] = 55 in our code, the value of list[0] will change to be 55. Here is an example code:


list = [3,4,1,20,102,3,5,67,39,28,10,1,4,34,1,6,107,99]

print list

print list[0]
print list[1]

list[0] = 55

print list[0]
print list

This code will output:

wpid-list_index_exampe_python-2013-10-24-15-30.png

Notice that the values of the list have changed after the assignment. Now let us recall the for loop syntax and properties in Python. The syntax is for element in sequence. That means that we need to provide a name of a variable, in this case element and a sequence such as a String, List, Tuple, etc. So if we wanted to print the numbers 1 to 10 in Python, we will need a list sequence with the numbers in a list and then we can just print element. Like this:


for element in [1,2,3,4,5,6,7,8,9,10]:
		print element

And the output:

wpid-1_to_10_python_for_loop-2013-10-24-15-30.png

Cool. However, what if we need the numbers 1 to 1,000? Well, you can either write them all in a list, or you can use the Python range function. This function has 3 variations. You can eithier call it with 1 integer, and the function will return the numbers from 0 to the number you requested in increments of 1. You can provide the function with a start number and end number (2 integers), and you will get back the numbers from the start to end in increments of 1. Finally you can give the range function 3 integers which will server as start, stop and increment. Here is an example to demonstrate:


# range with 1 argument, return a list with the numbers 1 to 10 in increments of 5
print range(10)

# range with 2 arguments, return a list with the numbers 5 to 10 in increments of 1
print range(5,10)

# range with 3 arguments, return a list with the numbers 5 to 50 in increments of 5
print range(5,50,5)

Output:

wpid-range_function_python-2013-10-24-15-30.png

Remember that the range function in not including the last number. So range(10) gave us the numbers 0 to 9 without 10. Lets combine the range function with indexing of the list to access and print the elements in a list.


list = [3,4,1,20,102,3,5]

for i in range(len(list)):
	print list[i]

This code will output:

wpid-python_list_example-2013-10-24-15-30.png

This is one way to do it. Note that we are using the Python len function to get the length of the list. Len is a built in function in Python and will return the length of any sequence.

Another way to accomplish the same task is to use Python and remove the indexing. Like this:


for element in list:
	print element

Both code output will be the same. There are some cases (as we are going to see) were we will need to use the first one and some where we are going to use the second. It all depends on your program. Now lets take a look and see how can we calculate the Average, Min, Max and Mode of a list. First what is the Average of a list? It is just the sum of the elements divided by the number of elements. Well, we can get the number of elements using the len function, and we can iterate through the elements and add them all up. Like this:


def avg(list):

	sum = 0
	for elm in list:
		sum += elm

	print “The average element of the list is: “ + str(sum/(len(list)*1.0))

That was very simple. Let me just clarify some things. You will notice that in the calculation we are multiplying everything by 1.0. We do this to make sure the length of a list, an integer is turned into a double. That way the result of the average element will not be rounded. We also need to convert the average from double to a string in order to concatenate it with a String.

Now let us move on to the Min/Max problem. Essentially both of these are two faces of the same coin. Here is our stragedy to solver this:

  1. Assume the fist element is our Minimum/Maximum value.
  2. For the rest of the elements in the array
  3. If you find a result smaller/larger than Minimum/Maximum, they are the new Minimum/Maximum
  4. return Minimum/Maximum

Hopefully that algorithm was easy enough to follow. Let us take a look how this looks like in Python:


def min(list):

	min = list[0]

	for elm in list[1:]:
		if elm < min:  			min = elm 			 	print "The minimum value in the list is: " + str(min) 	 def max(list): 	max = list[0] 	 	for elm in list[1:]: 		if elm > max:
			max = elm

	print "The maximum value in the list is: " + str(max)

And the output: (assume that: list = [3,4,1,20,102,3,5,67,39,28,10,1,4,34,1,6,107,99])

wpid-min_max_output-2013-10-24-15-30.png

Now let us to get to the hard part, computing the mode. This will turn out to be not so hard. What is the mode of a list? It is the number (or numbers) that occur most often. Ok. Now we are going to use 2 powerful tools Python has in it’s dictionaries and try-catch try-except statements. Dictionaries in Python are essentially lists where you can define the key. You can think about them as lists, but instead of an index that starts at 0 and goes up, you can name the key anything you would like. I would love to spend some time on them, but this might have to be another post by itself. Try-Catch Try-Except blocks are another post all by themselves, but think about them as a way to avoid TraceBacks. In other words if Python were to execute a statement that will result in a TraceBack, you can specify what to execute and the program will continue instead of terminate. I would love to talk mode about these 2, but for the time being you will have to read more about them on the Python Documentation or Google it.

So what i our strategy to find the Mode of a list? Well, first we can count the number of occurrences of each element in the list. We can use a dictionary to store the count and use the element themselves as the key. Let us see what that we give us:


list = [3,4,1,20,102,3,5,67,39,10,1,4,34,1,6,107,99]

d = {}
for i in t:
	try:
		d[i] += 1
	except(KeyError):
		d[i] = 1

print d

This will output the following:

wpid-dic_mode_python-2013-10-24-15-30.png

When we print out a dictionary we get all the keys and the values separated by a colon (:). We can also get all the keys in the list by typing d.keys(). That will give us a list of keys. Now the rest of the code involves finding the max of all values in the dictionary and then printing the keys that fit these values. Here is how that part looks:


for key in keys[1:]:
		if d[key] > max:
			max = d[key]

	print "The mode of the list is: ",
	for key in keys:
		if d[key] == max:
			print key,
	print " with the mode of: " + str(max)

wpid-mode_of_list_python-2013-10-24-15-30.png

Here is a link to the full code to Compute a Mode of a list in Python.

That’s it. We figured out everything we set to do in the beginning. But wait, there is more!

BOUNS Time: Find the range of the numbers in the list. That is super easy, especially now. The range of a list of numbers is simply the Maximum of your list minus the Minimum of your list. Since we alredy have function for that, this is super easy. Let’s take a look: (note a slight modification of the min/max functions is required to return values instead of print statements).


print "The range of the list is: " + str(max(list) - min(list))

By now you should have a better understanding of how lists work in Python. You will find out that all the tools we looked at are extremely useful and you will find them in every Python application. I am including here a full copy of the .py file I used to Compute the Mean, Min, Max, Mode and Range of a list in Python. I hope you have had some fun and learned something along the way. Here is the output of the complete program for:


list = [3,4,1,20,102,3,5,67,39,10,1,4,34,1,6,107,99]

wpid-python_list_data-2013-10-24-15-30.png

Any questions?

Problems, Programming Languages

The Basics Of Classes in Java

October 17, 2013

It has been a little while since I had a chance to write an article, so I figured I am way past due for one. Let us get started.

What are Classes? Classes are essentially blueprints. Much like a blue print for a coffee mug, house or a car. Classes contain a framework on which we can build an Object. Classes are the technical generic framework of an Object. So what are Objects? Well, the text book definition I tend to like is that Objects are instantiation of Classes. They are the “bringing to life” (if I may) of a Class. Let me try to put this into an example. A table in the most generic form would be a flat service supported by legs. This will be the Class. An Object of the table might be a kitchen table of hight h, width w, length l and has 4 rounded edges with round legs. The particulars of the Object are called attributes. We will get back to that in a little bit.

So what can Objects do for us? Well, the must be somehow useful, after all Java is an Object Oriented Programming Language and is by far the most in demand. Objects are useful because we can interact with them. We can use what we call behaviors, to make use of them. Going back to our example, what can we do with a table? We can put something on it and remove something form it. Maybe we can change it’s height by putting it on 4 bricks? I will admit when you think about it a table is a pretty simple Object, but when we see more examples we will see many more attributes and behaviors.

wpid-java-logo-2013-10-18-00-49.jpg

Before we get in to gory detail let us see more ways objects are useful. This following paragraph is mostly to convince you that Objects are indeed useful in any language. First, Objects allow us to create a hierarchy of an Objects that inherit information from their parents. What does that mean? It means that if for example we create a parent Object, call it Shape, we can create a child Object named Rectangle. The Object Shape might only have 1 attribute Name, but the Object Rectangle will have it’s parents attribute Name, and maybe some more information such as it’s sides lengths. Second, Objects allow us to encapsulate data. This means we can keep the internal of the Object hidden and keep the implementation as well as attributes hidden from another user. So in a nut shell I can write a program that uses an Object that I have no direct way to interact with it, aside from public methods. Third, because of encapsulation I can ensure the integrity of the attributes of an Object. For example, I can prevent anyone from leaving the Name of Shape empty. I know this is a little out there for someone that is just starting off, but like I said it is something you are going to have to learn and we will have to visit that later.

All this theory makes me want to code something up. How about that Rectangle class? Here is a problem formal definition:

Create a class Rectangle. The class has attributes length and width, each of which defaults to 1.0. It has methods that calculate the perimeter and the area of the rectangle. It has set and get methods for both length and width. The set methods should verify that length and width are each floating-point numbers larger than 1.0 and less than 10.0. Write a program to test class Rectangle.

This is a classic beginner problem and a good review/quiz problem. It shouldn’t take you longer than 10-15 min to figure something like this out. Lets try to work this out together. Like every other Computer Science problem, start by reading the problem at least twice and then start to figure out what is requested from you. Here is my list of requirements:

  1. Create a Rectangle class
  2. Rectangle has 2 attributes (or variables) length and width that are floating point numbers
  3. The attributes of Rectangle are initially set to 1.0.
  4. We need a getter and setter for each attribute
  5. The setter must validate that the number assigned to length or width is no less than 1.0 and no more than 10.0.
  6. Rectangle has to have a method to calculate perimeter and area.
  7. Write a main method that utilize Rectangle class and tests it’s functions.

Great. Now let us start with Java.

Number 1 is ease, create a Rectangle class. To do this we need the following code stored in a .java file with the same name as the class. In this case Rectangle.java.


public class Rectangle{

}

Well that was super easy. Now let us add the 2 attributes:


public class Rectangle{

	private double length;
	private double width;

}

Ok. That is still easy, but why is there the word “private” there? That is a variable modifier that tells Java what is the working scope of a variable or a method. There are 3 modifiers, private protected and public. Usually attributes of classes are private, at least in the beginning of programming. This is a whole other discussion by itself.

The next thing we need is called a constructor. A constructor is a method that is invoked when to Object is created. This is normally where the attributes are setup. The constructor has to have the same name as the class and does not have a return type like a normal function would have. Here is what our default constructor will look like for Rectangle.


public Rectangle(){
	this.length = 1.0;
	this.width = 1.0;
}

Notice that we used the modifier this to denote the class attribute and not a local variable length. This is not a must, but it will make you life easier and in some cases save you a lot of time figuring out why things are not working like you except. The constructor we have is the empty constructor. It is not a must, like I said. If you do not write a constructor, Java will inherit one from the generic Class definition. That means that nothing will happen beside Java giving your variable an address.

Moving forward (or downward) in our list we need a getter and setter for each attribute. Remember a few paragraphs ago I mentioned something about data integrity? This is where the getter and setters com in to play. They act as a buffer between the user and the values of the attributes. In the case of getters they just return the value (normally). In the case of setters we can modify the actual attribute only if it is an acceptable value. In our case we can write our setters such that if the values are less than 1.0 or more than 10.0 the value of the Object is not set. Let’s take a look:

Here are our getters:


public double getLength(){
	return this.length;
}

public double getWidth(){
	return this.width;
}

And here are the setters:


public void setLength(double length){
	if((length >= 1.0) && (length <= 10.0))           	this.length = length; } public void setWidth(double width){ 	if((width >= 1.0) && (width <= 10.0))
          	this.width = width;
}

That was not so bad, was it? Before we move on to testing we have to complete 1 more task, writing a method for computing perimeter and area. That should be really straight forward.


public double perimeter(){
	return 2 * (this.length + this.width);
}

public double area(){
	return this.getLength() * this.getWidth();
}

You will notice that in the perimeter method we used this to access the variables, while in the area method we used the getters. Both styles are ok and will yield the same results. This was done for educational purposes only.

So now we are done with our class and can move on to testing. Wrong! I highly recommend you take the time to write a debug toString() method. Why? you will thank me later. Here is my toString() for Rectangle:


public String toString(){
	return "Length: " + this.length +"\tWidth: " + this.width;
}

It may seem simple, but later when you are dealing with multiple classes, it is nice to just be able to print them. Let us try to actually use our class. We are going to use a Scanner for user input and standard user output (terminal screen). Here is a simple Main I put together. If you find it useful here is a link to Java Rectangle Class.


public static void main (String[] args)
{

	Scanner userInput = new Scanner(System.in);
	Rectangle r = new Rectangle();

	System.out.print("Enter a length >>> ");
	r.setLength(userInput.nextDouble());

	System.out.print("Enter a width >>> ");
	r.setWidth(userInput.nextDouble());

	System.out.println("The Rectangle with the following attributes: \n" + r);
	System.out.println("Has perimeter is:  " + r.perimeter() + " and area is:  " + r.area());

}

And the output:

wpid-java_rectangle_output-2013-10-18-00-49.png

That is all. Easy isn’t it?

Computer Programming I

A Quick Tutorial for Python Syntax

July 8, 2013

For some, Python is far from their first language. For others, it is where they had started programming. I have received several comments and emails from readers asking how to proceed after understanding the basic concepts in Python. I am hoping to put together a road-map into Python in the next few weeks. Whether you know Python already or want to learn the basic quickly, I hope you will find this post (and the rest) useful. This is a very quick paste, high overview of the language. You are expected to know the basics of programming. Think of this as fast Python syntax review. For this tutorial I will use Python2.7. I highly recommend you consult the Python2.7 documentation while coding or download Python2.7 documentation for offline use. Linux and Mac come with Python already pre-installed. If you require help setting up a Python environment, please consult the Python installation guide. I am going to assume from this point on you already have Python 2.7 at least installed on your system. So let us get to it:

Running Python

There are 3 ways to execute Python code:

  1. The Python Interpreter - an interactive terminal. Statements are evaluated as entered.
  2. Loading a file into the Python Interpreter - save any text file as a .py and execute the statements.
  3. Compiled Python - this is not for speed of execution, rather for sharing a program without sharing code.

For any of the ways, we are going to focus on command line only. There are IDEs for Python, however they are an overkill for this tutorial. To run Python, simply lunch your terminal and type ‘python’. If you want to run a .py file in the terminal type ‘python <file_name.py>’, where file_name should be replaced with your file name.

Comments

In Python, any line starting with the ‘#’ symbol is considered a comment and will be ignored by the Interpreter.

Python Basic Data Types

Similar to other languages, Python supports the idea of basic data types. Unlike most low-level languages, Python does not require the programmer to specify the type. Python interrupter takes case of the data type for you. You may also change to type throughout the program. Thankfully, Python has a built in function type() that can clarify what type of data Python ‘thinks’ the variable is. The basic data types are:

* integer
* long
* float
* complex
* string
* boolean

Here is an output from the Python interpreter:

wpid-pythonbasicdatatypes-2013-01-20-10-09.png

Python Data Structures

Python has 4 data structures that could be at your disposal. These are complex data types that are built from the basic data types we saw before. Each of the data structure types has different usage and attributes. We will discuss:

* Lists
* Tuples
* Dictionaries
* Sets

Starting from the top, Lists are the most common data structure used in Python. With Lists you can group basic datatypes or even data structures together. You can preform numbers standard library function on lists. The 2 (2things) most important things to remember about lists are:

* They are 0 and reversed numeric indexed
* They are mutable

Let us look at some list example operations:

wpid-pythonlists2-2013-01-20-10-09.png

Moving on to tuples, they are very similar to lists but with one thing apart. Tuples are immutable. You may think of tuples as immutable lists, in other words lists that can not be changed once you create them. All the operations we have done on lists apply to Tuples, however, we cannot remove or add elements. This means that when we initiate a Tuple we initiate it with values that may never change. Let us look at some simple Tuple operations:

wpid-pythontupleexamples2-2013-01-20-10-09.png

So now that we have some data types we can move on to the next vital piece of information you need to know, Python Standard Library. Python include a huge array of functions you can use without anything special. The type() and len() functions are some examples of the functions that are included in standard library. This also includes function such as input() and raw_input(), string and number manipulation and many more functions. The best advice if you are looking for a function, check if it is included in stadard library before going to far.

So now what do we do if a function is not in standard library. For example, lets say we need to comute a sin() of an angle, or require the value of pi for calculation, what do we do then? Well, in that case we can import a library. That is right, in addtion to the huge standard library there is also a "secondary library" with everything you might think about, at least in the beginning. Again, you can refer to the Python2.7 documentation for any reference to these libraries. In our case we can import the math library and directly call the math.sin() function or access the value of math.pi. Let us take a look:

 

python_math_import_example3

 

Python is truly a fun language to begin to code with. I did not begin with Python myself, but I highly recommend it to others. Why? well, first I do not think anyone should start in PASCAL any more. Although it was a good educational languages, it is pointless to learn today. Second, Python is natural. It is easy to ease in to programming with python far more than any other language. (This last point might be debatable on the person and the teacher).

Passwords

Authentication of Users and Passwords in Python

January 29, 2013

Before we dive in to the topic, I would like to apologies. Over the past 10 days, I have had multiple matters that require my attention. While I try to allocate some time for everything, this blog has not been on the top of my priorities. This was a mistake, I now realize. I should have anticipated some of the issues and plan ahead accordingly. The opposite is what happened. I cannot say this will not happen again, I can only apologies and try to do better in the future. So let us get started.

The last post I wrote talked about how to password protect your python program. Although this is very neat and sufficient in most cases, what you really need is a method to authenticate users and password. This post will be rather simple and straight to the point. Much of the work it relies on we have done already. Recall at this point we are storing the password as encrypted strings in a file, independent of our python program. Now we just have 2 things we have to do. We will start by recognizing a single user and allow him/her accesses. Then, we will expand the program to allow multiple allowed users accesses. As noted before, we are going to use Python2.7, I strongly encourage referring to the documentation or download the documentation for python2.7 for offline reference.

As we did previously, before we can authenticate any user we have figure out how we want to store the data we are comparing to. You may recall we used a support program to create a file and store the password. Now we will extend the “helper” script to store a user name on a single line, followed by the encrypted password in the next line. This format may be modified at your discretion. For example, you may choose to encrypt both the user name and the password. You may also choose to have all the information as a single line, separated by a vertical line, ‘|’, or a comma, ‘,’. The options are multiple, but the principle is the same. Assuming we follow the first suggested format, here is how the code to store a user name and password will look like:


import sys
import hashlib
import getpass

def main(argv):

	if len(argv) != 1:
		sys.exit('Usage: store_user_pass.py <file_name>')

	print '\nUser & Password Storage Program v.01\n'
	
	if raw_input('The file ' + sys.argv[1] + ' will be erased or overwrite if exsting.\nDo you wish to continue (Y/n): ') not in ('Y','y') :
		sys.exit('\nChanges were not recorded\n')
	
	user_name = raw_input('Please Enter a User Name: ')
	password = hashlib.sha224(getpass.getpass('Please Enter a Password: ')).hexdigest()

	try:
		file_conn = open(sys.argv[1],'w')
		file_conn.write(user_name + '\n')
		file_conn.write(password + '\n')
		file_conn.close()
	except:
		sys.exit('There was a problem writing to the file!')

	print '\nPassword safely stored in ' + sys.argv[1] + '\n'		
			
if __name__ == "__main__":
	main(sys.argv[1:])

Note that the changes from our previous version, store a single encrypted password, have not changed much. The main thing we have done is added a user_name variable that gets written to the file. As before, we warn the user from alteration of a file might already exist. Here is an example output of the program:

wpid-userandpasswordstorage-2013-01-21-16-37.png

Here are the content of the file pass_db.txt:


cptdeadbones
99fb2f48c6af4761f904fc85f95eb56190e5d40b1f44ec3a9c1fa319

Now we are ready to see how the other side of this program might look like. Since we know how to verify the password, adding the user name option is not much change. For our application purpose, we will terminate the program if the user name is not known or x password attempts have been made. Here is how the code for this will look like:


import sys
import hashlib
import getpass

def main(argv):

	if len(argv) != 1:
		sys.exit('Usage: user_pass.py <file_name>')

	print '\nUser & Password Authentication Program v.01\n'

	try:
		file_conn = open(sys.argv[1])
		user_name = file_conn.readline()[:-1]
		password = file_conn.readline()[:-1]
		file_conn.close()
	except:
		sys.exit('There was a problem reading the file!')
		
	pass_try = 0 
	x = 3
	
	if raw_input('Please Enter User Name: ') != user_name:
		sys.exit('Incorrect User Name, terminating... \n')
	
	while pass_try < x:
		user_input = hashlib.sha224(getpass.getpass('Please Enter Password: ')).hexdigest()
		if user_input != password:
			pass_try += 1
			print 'Incorrect Password, ' + str(x-pass_try) + ' more attemts left\n'
		else:
			pass_try = x+1
			
	if pass_try == x and user_input != password:
		sys.exit('Incorrect Password, terminating... \n')

	print 'User is logged in!\n'		
			
if __name__ == "__main__":
	main(sys.argv[1:])

Running the code with the file we generated before, pass_db.txt:

wpid-userpassverify-2013-01-21-16-37.png

Like previous programs, the user is prompt for a password 3 times. At each trial the user is notified the number of password attempts reaming. At this point, if you have been following along, you should be able to pice together how this might be extended to multiple users. For our final version we will have 2 python files, one to generate a password file and the other to log the user in. The modification for the storage code needed at this point are minimal, all we need to change is the mode we write to the file. In previous versions we used ‘w’ for write mode. Now we are going to use ‘a’, which is only going to append the new information to the end of the file. If the file is not yet created, the file will be created.You can look users and password storage program.

Last but not least, here is our final version of the authentication module. First the code:


import sys
import hashlib
import getpass

def process_file(file_name):
	
	user_names = []
	passwords = []
	
	try:
		file_conn = open(file_name)
		data = file_conn.readlines()

		for i in range(len(data)): 
			if i%2 == 0:
				user_names.append(data[i][:-1])
			else:
				passwords.append(data[i][:-1])
			
		file_conn.close()
	except:
		sys.exit('There was a problem reading the file!')
		
	return user_names, passwords

def main(argv):

	if len(argv) != 1:
		sys.exit('Usage: user_pass.py <file_name>')

	print '\nUser & Password Authentication Program v.01\n'

	user_names, passwords = process_file(sys.argv[1])
		
	pass_try = 0 
	x = 3
	
	user = raw_input('Please Enter User Name: ')
	
	if user not in user_names:
		sys.exit('Unkown User Name, terminating... \n')
		
	while pass_try < x:
		user_input = hashlib.sha224(getpass.getpass('Please Enter Password: ')).hexdigest()
		if user_input != passwords[user_names.index(user)]:
			pass_try += 1
			print 'Incorrect Password, ' + str(x-pass_try) + ' more attemts left\n'
		else:
			pass_try = x+1
			
	if pass_try == x:
		sys.exit('Incorrect Password, terminating... \n')

	print 'User is logged in!\n'		
			
if __name__ == "__main__":
	main(sys.argv[1:])


So what is different? Now instead of just reading one user name and password, we read more. The information is stored in 2 (2things) lists that have corresponding indexes. So the user name at index 1 has an encrypted password stored at index 1 of the password list. All other operation are the same as any previous example. I do not think there is a need to include an input, it is the same as before.

For a final remark, I realize that the method I discussed in this and the previous post and this one are not very secure or useful outside of an educational exercise. In ‘real world’ applications the information will be stored in a database. There are some software that has already been pre written for user authentication in python. The bottom line is that user authentication is not enough to protect an application. There are several more methods we may or may not cover in the future. For the near time, we will start to look into security algorithms and application.

Passwords

Password Protecting Your Python Application

January 18, 2013

Couple weeks back we talked about how to generate passwords in python. Now, I would like to explore how to password protect your application. We will be using Python again, only this time I will upgrade to Python2.7 due to popular demand. You can reference to Python2.7 the documentation or download Python2.7 documentation.

There are many situations in which you would like to password protect the application. It could be just a simple application you do not want anyone else to run, or it could be an application that stores sensitive data. The two things you need to keep in mind is that authentication is independent of the application and that we are discussing application authentication. That is, the ideas may apply to web, mobile & other applications, however, we are going to limit this discussion to python application.

Lost You Password?<a href="http://c9d568r8ox3aii95ujuky1vcxo.hop.clickbank.net/" target="_top">Click Here!</a>

Let us start by assuming there is an application we wish to secure. For demonstration purpose, the application will simply print out:

User is logged in!

Otherwise an appropriate error message will be displayed. We can agree that the print statement can be replaced with a function call to start an application. We are going to start with the simplest case. We have a string password that is stored in a variable. We prompt the user for a password. If the user input does not match the stored password, we terminate the application without letting the user log in. Here is what that would look like in code:


import sys

def main():

	print '\nPassword Request Program v.01\n'

	password = 'abcd'
	user_input = raw_input('Please Enter Password: ')

	if user_input != password:
		sys.exit('Incorrect Password, terminating... \n')

	print 'User is logged in!\n'

if __name__ == &quot;__main__&quot;:
	main()

And the output of the program in both cases:

password auth 1_1

password auth 1_2

You can see that the first time the user entered ‘password’ for the password. The program recognizes an incorrect password and is terminated. The second time the user entered the correct password ‘abcd’ and the user was successfully logged in. For a simple application, this might be enough. However, we are going to take this idea much further. To start, let us add the ability for the user to try to enter a password x amount of times before the program is terminated. For now, let us assume x is 3. You might change the value of x to any number you wish. Our modifed program might look like this:


import sys

def main():

	print '\nPassword Request Program v.02\n'

	password = 'abcd'
	pass_try = 0
	x = 3

	while pass_try &lt; x:
		user_input = raw_input('Please Enter Password: ')
		if user_input != password:
			pass_try += 1
			print 'Incorrect Password, ' + str(x-pass_try) + ' more attempts left\n'
		else:
			pass_try = x + 1

	if pass_try == x and user_input != password:
		sys.exit('Incorrect Password, terminating... \n')

	print 'User is logged in!\n'

if __name__ == &quot;__main__&quot;:
	main()

Sample output:

password auth 2_2_2

password auth 2_2_1

If you examine the code you might notice a few different things. We have a while-loop that runs for x amount of times. This might be replaced with a simple for-loop, but keep in mind that there is no guarantee that the user will need any incorrect attempts. In addition, if you do use a for loop, you might need to use a break statement, which is not a good programming habit. You might also notice that that the program notifies the user how many attempts he or she has left. This is not required, but as a user it is nice to know.

As you examine the code, you will soon realize that storing the password in the code as a string is not the best practice. Let us move the password into a file. This way we can separate the password from the program. The path for the file will be given as a command line argument. The file can by anywhere in the file system, including on a USB drive. Without it, the program will not run and terminate immediately. For this example, we will store the password in a plain txt file called pass_file1.txt. Here is the content of the text file:


abcd

Here is our new version, using the file to store the password:


import sys

def main(argv):

	if len(argv) != 1:
		sys.exit('Usage: pass_auth3.py &lt;file_name&gt;')

	print '\nPassword Request Program v.03\n'

	try:
		file_conn = open(sys.argv[1])
		password = file_conn.readline()[:-1]
		file_conn.close()
	except:
		sys.exit('There was a problem reading the file!')

	pass_try = 0
	x = 3

	while pass_try &lt; x:
		user_input = raw_input('Please Enter Password: ')
		if user_input != password:
			pass_try += 1
			print 'Incorrect Password, ' + str(x-pass_try) + ' more attempts left\n'
		else:
			pass_try = 4

	if pass_try == x and user_input != password:
		sys.exit('Incorrect Password, terminating... \n')

	print 'User is logged in!\n'

if __name__ == &quot;__main__&quot;:
	main(sys.argv[1:])

And here is some sample output. Notice that the first try is without giving the program a path to a file.

password auth 3_2_1
password auth 3_2_2
password auth 3_2_3

Take a closer look at the code. You will notice that there is more than one way the program can might terminate. If a file is not provided the program will terminate immediately. If there are any issues reading the file the program will terminate. Finally, if the password is incorrect more than x times the program will terminate. When reading from the file we use the readline() method. This will read an entire line from the file, including the newline character ‘\n’. This is why there is an added [:-1] to trim the string to not include the newline character.

So far we have seen how to ask for a simple password. However, this is far from a real-world application strength. The problem is that the password is stored as a plain text file. This means that if anyone was to open it, they will know your password immediately. As a good programmer, you do not want a client to find out their secure passwords are stored in plain text. Much less a user finding that out. Or worse. To solve this problem we will introduce 2 (2things) new ideas. First a method to avoid seeing the characters as the user types. Second, we will encrypt the password we store in the file using one way encryption.

In order to hide the password while the user is typing, we will use a python standard library named getpass. The library is quite small, but provides exactly what the name suggests and nothing else. Here is a simple example of how the library works:

wpid-getpassexample-2013-01-17-20-47.png

Basically, getpass.getpass() is equivalent to using raw_input(), but hides the typed characters. I think it is rather straight forward why you should use this library when asking a user for a password. Moving on to the second thing, we need a way to encrypt our password. Furthermore, we want our password encrypted using a one way encryption method. This means that once we encrypt the data, there is no simple function to retrieve the data. Python has a multiple ways to achieve this using standard library functions. We will use a built-in library called hashlib that provides many encryption methods. I choose to follow on of the examples and use sha224 with conversion to hex. Here is an example of using sha224:

wpid-shaexample-2013-01-17-20-47.png

You can see that the encrypted string has nothing to do with the string ‘password’. So how are we going to use one way encryption? Simple, we are going to store the original encrypted password in the file. Then when the user enters a password we will encrypt the user input exactly the same way and compare the encrypted string from the file. If we do not use the same encryption algorithm, this method will not work. You may change the encryption algorithm to what every method you like. Since we need to encrypt the passwords, we will need a helper program to store the password before we modify the authentication program. Here is an example program to store the an encrypted password:


import sys
import hashlib
import getpass

def main(argv):

	if len(argv) != 1:
		sys.exit('Usage: store_pass.py &lt;file_name&gt;')

	print '\nPassword Storage Program v.01\n'

	if raw_input('The file ' + sys.argv[1] + ' will be erased or overwrite if existing.\nDo you wish to continue (Y/n): ') != 'Y' :
		sys.exit('\nChanges were not recorded\n')

	password = hashlib.sha224(getpass.getpass('Please Enter a Password: ')).hexdigest()

	try:
		file_conn = open(sys.argv[1],'w')
		file_conn.write(password + '\n')
		file_conn.close()
	except:
		sys.exit('There was a problem writing to the file!')

	print '\nPassword safely stored in ' + sys.argv[1] + '\n'

if __name__ == &quot;__main__&quot;:
	main(sys.argv[1:])

Here is an example output for this program:

wpid-storepass1-2013-01-17-20-47.png

The program is fairly simple. First we verify that the user acknowledges that if the file exists already it will be erased. There are other ways around this, but this is one of the simple solutions. You do not want to assume the user entered the right file name the first time. If you were to use a file name that already exists, the file will be permanently altered. Since we opened the file in write mode, we will erase any information already there. This is why you should double check that the user entered the correct file name. Of course, you do not have to do it and you may erase the associated if statement.

As a last note, we do not store the plain value of the password in a variable. Instead it is transferred directly to the encryption method. This offers some extra security to you program. Finally, we write the information to the file and terminate the program. If we were to look at the content of pass_file2.txt we will see something like this:


a76654d8e3550e9a2d67a0eeb6c67b220e5885eddd3fde135806e601

Now we are ready for our final version of password authentication, using the encrypted password file. Here is the code for it:


import sys
import hashlib
import getpass

def main(argv):

	if len(argv) != 1:
		sys.exit('Usage: pass_auth3.py &lt;file_name&gt;')

	print '\nPassword Request Program v.04\n'

	try:
		file_conn = open(sys.argv[1])
		password = file_conn.readline()[:-1]
		file_conn.close()
	except:
		sys.exit('There was a problem reading the file!')

	pass_try = 0
	x = 3

	while pass_try &lt; x:
		user_input = hashlib.sha224(getpass.getpass('Please Enter Password: ')).hexdigest()
		if user_input != password:
			pass_try += 1
			print 'Incorrect Password, ' + str(x-pass_try) + ' more attempts left\n'
		else:
			pass_try = 4

	if pass_try == x and user_input != password:
		sys.exit('Incorrect Password, terminating... \n')

	print 'User is logged in!\n'

if __name__ == &quot;__main__&quot;:
	main(sys.argv[1:])

Notice that not much has changed. What we have added is applying the same encryption method we did to the file, to the user input. Here is how the program looks like when it runs:

password auth 4_1

password auth 4_2

We have explored adding a password security to your python program. If you really want to use it, you will need to conceal your code. One way to conceal your code is to compile code to a pyc file. This is just one way you might do this. There are other methods you could explore to create executable from p a py file. We will not explore them within this post. For the moment, I will leave you with a pyc file and a file containing an encrypted password. The application will have a unique output. Can you make the application run?

pyc riddle file
passwod file

Mathematics

How to Find Prime Numbers in Python

January 6, 2013

To mathematicians prime numbers represent a certain Nobel challenge. They have been studying prime numbers for a while, trying to learn their properties. Some mathematicians actually made progress. Others have gone insane trying to prove a pattern or how to generate the nth prime. Some are actively looking for the largest prime they can find. For computer scientists and programmers prime numbers have properties that can be utilized in many areas. Cryptography and pseudo-random number generators are 2 examples applications of prime numbers. Let us take a dive into the world of prime numbers. We will look at how we can generate and validate prime numbers in python.

Any valid math discussion must begin with a definition. Here is a definition of prime numbers I like to use:

“A natural number p > 2 is called prime if and only if the only natural numbers that divide p [without reminder] are 1 and p. A natural n > 1 that is not prime is called composite. Thus,, n > 1 is composite if n = ab, where a and b are natural numbers with a > 1 and b < n. “ Discrete Mathematics with Graph Theory

What does this means? It means that a number, for example 17, is prime if and only if it can be divided only by 17 and 1. On the other hand, 18 is not prime. 18 is a composite number that can be written as 2 x 9 or 3 x 6. This will prove to be a very useful property.

So how do we find prime number? Well, we do not. Or not exactly. Since the natural number are infinite and a prime number can be any number greater then 2, by definition there are infinite prime numbers. Many mathematicians have tried to prove a formula or correlation among prime numbers. None to date have succeeded. The best we can do is to generate a number and check if it is prime. However, there are some tricks we can do to speed things up, but we will get to that.

Here is our basic problem. We want to generate all the prime numbers between x and y. For starts, let us think about the numbers between 2 and 100. The straight forward, brute force, approach will be to check every number in that range and see if any number up to it can divide it without a reminder. If we find such number then it is not prime. Let us take a look at a simple program that can do this for us:


import sys

def is_prime(num):
	for j in range(2,num):
		if (num % j) == 0:
			return False
	return True

def main(argv):

	if (len(sys.argv) != 3):
		sys.exit('Usage: prime_numbers.py <lowest_bound> <upper_bound>')

	low = int(sys.argv[1])
	high = int(sys.argv[2])

	for i in range(low,high):
		if is_prime(i):
			print i,

if __name__ == "__main__":
	main(sys.argv[1:])

And the output for prime numbers between 2 and 100:

wpid-pythonfirst100primes-2013-01-6-09-56.png

Now for some tricks. First, we don’t have to check every second number. All the even numbers will be divisible by 2 by definition of even numbers. So our first loop can be rewritten to jump by 2 and start at an odd number. That way we are just checking the odd numbers. By this hypothesis, all odd number are potentially a prime number. This takes away half the numbers we need to check. If we were to ask for all the prime numbers between 100 and 10,000 it might take a while. Lets look at how long it will take my computer (Intel core duo 2 2.53GHz with 8GB ram) to run this program using the unix time command.

The original script from before:

wpid-pythontimetocalculateprimes1-2013-01-6-09-56.png

Modified script to take out the evens numbers:


import sys
import math

def is_prime(num):
	for j in range(2,num):
		if (num % j) == 0:
			return False
	return True

def main(argv):

	if (len(sys.argv) != 3):
		sys.exit('Usage: prime_numbers2.py <lowest_bound> <upper_bound>')

	low = int(sys.argv[1])
	high = int(sys.argv[2])

	if (low == 2):
		print 2,

	if (low % 2 == 0):
		low += 1

	for i in range(low,high,2):
		if is_prime(i):
			print i,

if __name__ == "__main__":
	main(sys.argv[1:])

wpid-pythontimetocalculateprimes2-2013-01-6-09-56.png

This modification cut the program time by nearly half, but we can do better. According to the Sieve of Eratosthenes we do not need to check if all the numbers will divide our potential prime, we only need to check up to the floor of the square root of the number. So our next version of the code will look like this:


import sys
import math

def is_prime(num):
	for j in range(2,math.sqrt(num)):
		if (num % j) == 0:
			return False
	return True

def main(argv):

	if (len(sys.argv) != 3):
		sys.exit('Usage: prime_numbers3.py <lowest_bound> <upper_bound>')

	low = int(sys.argv[1])
	high = int(sys.argv[2])

	if (low % 2 == 0):
		low += 1

	for i in range(low,high,2):
		if is_prime(i):
			print i,

if __name__ == "__main__":
	main(sys.argv[1:])

And the time to find all the primes between 100 to 10,000:

wpid-pythontimetocalculateprimes3-2013-01-6-09-56.png

This is really great. We have improved our program by another half and nearly a quarter than the original run. Let us examine 2 (2 things) variations of this program. First we will calculate the nth prime number. Second we will try to get a random prime number for a given length.

In order to calculate the nth prime we will have to modify them main() loop into a while loop. We will also modify the program to accept only 1 number, the nth prime we want to calculate. Once we reach the nth prime we will print it out.


import sys
import math

def is_prime(num):
	for j in range(2,int(math.sqrt(num)+1)):
		if (num % j) == 0:
			return False
	return True

def main(argv):

	if (len(sys.argv) != 2):
		sys.exit('Usage: prime_numbers4.py <nth_prime>')

	i = 0
	num = 2
	nth = int(sys.argv[1])

	while i < nth:
		if is_prime(num):
			i += 1
			if i == nth:
				print 'The ' + str(nth) + ' prime number is: ' + str(num)
		num += 1

if __name__ == "__main__":
	main(sys.argv[1:])

Sample output:

wpid-pythontimetocalculateprimes4-2013-01-6-09-56.png

For many application computing a prime number is not enough. For some we want a specific length of prime number. Lets say we need a 5 digit prime number. How are we to calculate this? The simple approach is to generate all 5 digits prime numbers and choose 1 of them randomly. Let us look at how to do this:


import sys
import math
import random

def is_prime(num):
	for j in range(2,int(math.sqrt(num)+1)):
		if (num % j) == 0:
			return False
	return True

def main(argv):

	if (len(sys.argv) != 2):
		sys.exit('Usage: prime_numbers5.py <num_digits>')

	digits = int(sys.argv[1])
	low = int('1' + '0' * (digits-1))
	high = int('9' * digits)
	prime_number_list = []

	if (low == 1):
		prime_number_list.append(2)
		low = 3

	if (low % 2 == 0):
		low += 1

	for i in range(low,high,2):
		if is_prime(i):
			prime_number_list.append(i)

	print 'A random ' + str(digits) + ' digits prime number is: ' + str(random.choice(prime_number_list))

if __name__ == "__main__":
	main(sys.argv[1:])

Output:

wpid-pythontimetocalculateprimes57-2013-01-6-09-56.png

If you were to run the program, you will notice that the it will take longer and loner as n gets larger. I found that for any n grater than 6 digits, it is very demanding on the hardware. I do not recommend letting this program try to calculate a high digit prime. You will also notice if you try to ask for 10 digits, python will raise an error in the range function. So how do we compute n digit prime for a large n? One way I found is by using a random number and checking if it is prime. This seems to work reasonably well with numbers less than 15, but then again it is random.


import sys
import math
import random

def is_prime(num):
	for j in range(2,int(math.sqrt(num)+1)):
		if (num % j) == 0:
			return False
	return True

def main(argv):

	if (len(sys.argv) != 2):
		sys.exit('Usage: prime_numbers6.py <num_digits>')

	digits = int(sys.argv[1])
	low = int('1' + '0' * (digits-1))
	high = int('9' * digits)
	done = False

	if (low == 1):
		low = 2

	while not done:
		num = random.randint(low,high)
		if is_prime(num):
			print 'A random ' + str(digits) + ' digits prime number is: ' + str(num)
			done = True

if __name__ == "__main__":
	main(sys.argv[1:])

wpid-pythontimetocalculateprimes58-2013-01-6-09-56.png

So how about really large primes? That is where time becomes an enemy and computational complexity goes up. I found a few modules that can help compute large primes in python but I have yet to try to run anything. Once I get a chance I will try to run them and put a post up. If you really need prime numbers I would advise you to either download a list of them or generate a list of primes and save them to a text file. Prime numbers will show up every once in a while. They come up in cryptography and other encryption methods. Most usage of prime numbers is due to the nature of the numbers. For more information about prime numbers I would suggest seeking out a mathematician, which I am clearly not.

Programming Languages

Programming Languages to a Non-Programmer

December 24, 2012

As a non-programmer, you have often heard programming languages names being used. Marketers have always tried to used technical words to market new products and to claim superiority using “fancy” words. Many have come across HTML, java, flash, but do not know what that means. It is to my intend to educate those who may not know.

As for the programmers among you, many of us do not go a day without using several programming languages. If you really think about it, after the first few languages, learning new ones become easier. This may not encompass human languages, but learning new computer languages became easier for me with time. One thing that helped me the most was learning about the different types of programming languages. Knowing where to categories a new language helped me relate things I already know with new information. Hopefully you too will find this true. Learning new programming languages is a vital tool any programmer needs to acquire.

A Programming language is a communication method for humans to interact with machines. That is a very high level view. Machines, computers to be exact, work on binary sequences. That is strings of 0’s and 1’s. At the end of the day that is all computers understand. Further more, the entire operations a computer knows how to do is limited to operations on those strings of 0’s and 1’s. Any more complicated operations is done via multiple operations on said strings. Thankfully, we can store and reuse a sequence of operations. This is the closet level of operations, Machine Language. In the early days of computing, computers were programmed in such method. However, it is very impractical to program anything complex in this matter. Every set of commands in any languages must end up as a Machine Language instruction set suitable for a target computer architecture.

To take a step farther form Machine Language, we created Assembly. Assembly is the attempt to combine machine language operations into symbolic ones. It often group several Machine Language instructions into a single Assembly command. This enables programmer to create more complex programs, however still resides close to Machine Language. It provides better readability, with the same efficacy of Machine language. Assembly instructions are compiled into their Machine Language representations in order to be executed on a target architecture.

The next step away from Machine Languages are the low and high level programming languages. Some are easy to specify as while others are in-between. Languages that allow direct access to memory are often considered low. Languages such as c, c++, java to some extend, are low level. High level languages include matlab, matamitica, php, and other. Python for example, could be argued to be somewhere in-between. Depending on the programmer and the libraries used, python could be utilized as a low level or a high level language.

There are many types of programming languages. The Wikipedia entry for List of programming languages by type counts 43 languages as of the date of this post. Some of the ones I highly recommend on learning are (in no particular order of preference):

  • c, java, python
  • Lisp
  • Prolog
  • web langs: php, javascript, mysql, html, css
  • matlab
Computer Programming I

Computer Programming I

September 4, 2012

After writing about the content of Computer Programming III and writing the assumptions for that, I had a friend take a look. The most obvious problem was that I didn't define part I and II. So the following is what I would use as a syllabus for Computer Programming I.

 

Please NOTE: The associated web pages with Computer Programming I are for absolute beginners. The key audience for these pages are people who want to start programming. Although some of the post may be relevant for non-beginners, please be patient when reading. As always if you find any errors, please do point them out via email or in the comments.

 

Assumptions

Going back to My first assumptions, the following assumptions still hold true.

Assumption #0: You can read and write.

Assumption #3: You have Internet access.

Assumption #4: MATH.

Assumption #5: Hardware & Software.

 

The main purpose of Computer Programming I is to peak your interest. By the end of the first programming class you should be at a point where Assumption #2: You want to know more is a constant. You will learn about what programming can do and what are the limitations. That being said, you will not get to a point where you need a super fast computer, or run out of memory. You might get the computer to freeze, but not because of computation. Before I get to the syllabus and the specific topics, the following are the topics in no particular order.

Topic #0: Basic Building Blocks. This is the most fundamental programming. types, conditionals, program flow, basic proof, etc. This is will give you all the tools to start writting programming.

Topic #1: Functions. I can not explain how important this part is. Ask any programmer in any language. Functions will become the biggest tool in you arsenal.

Topic #2: Object Oriented Programming.  An introduction to OOP concepts and basic maneuvering.