Sunday, June 30, 2013

Java: Rock, Paper, Scissor Game Source Code

This is the source code for how to implement a rock, paper, scissor game in JAVA. It has a swing GUI interface (using JOptionPane) that prompt the user for input.

 
// A game that plays rock paper scissor with user

import javax.swing.JOptionPane;

public class GameRockPaperScissor {
 public static void main(String[] args) {
  // Prompt the user to input the option they choose
  String humanInput = JOptionPane.showInputDialog(
    "Enter rock, paper, or scissor:");
  // Convert to lower case
  humanInput = humanInput.toLowerCase();
  
  // Generate a random number
  // Scissor (0),  rock (1), paper (2)
  int random = (int)(Math.random() * 3);
  String computerInput; // Computer's choice
  if (random == 0) 
   computerInput = "rock";
  else if (random == 1)
   computerInput = "paper";
  else
   computerInput = "scissor";
  
  String message = "The computer is " + computerInput + ". You are "
    + humanInput;
  
  // Determine who win
  boolean isTie = computerInput.equals(humanInput);
  boolean isWin = 
   ((computerInput.equals("rock") && humanInput.equals("scissor")) ||
   (computerInput.equals("paper") && humanInput.equals("rock")) ||
   (computerInput.equals("scissor") && humanInput.equals("paper")));
  
  // Prepare the message
  if (isWin)
   message += ". Computer Won.";
  else if (isTie)
   message += " too. It is Tie";
  // There are 3 options, computer win, tie, or you win
  // So we don't have to test here, if the code reach here, human win.
  else
   message += ". You Won";
   
  
  // Display the result on the screen
  JOptionPane.showMessageDialog(null, message);
 }
}

Thursday, May 31, 2012

Blog Index

I have been writing tutorials and posting different projects for a while now, I decided to write an index for easy look up for the different post. They are divided to a few section as the follow. I hope you can find what you are looking for, if not, try to use the search feature located in the lower right side. If you have an question, please feel free to email me or leave me a message in the comment.

Python Tutorial
  • Python Reference
    A list of useful website and textbook review
  • csci133c1.py
  • Basic Hello World, declare variables, simple for loop control statement
  • csci133c2.py
  • Nested for loops, list, counting, if statement
  • csci133c3.py
  • Introduction to function, string's class function, useful tip for handling string
  • csci133c4.py
  • Opening a file, and using everything we know together. Additional to a brief review practice problem, introduce dictionary
  • csci133c5.py
    Talks about function, what are they, how to define them
  • csci133c6.py
    A taste of python's GUI, Tkinter. Introducing the title, frame, button, input widget, and what they can do with each other
  • csci133buildin.py
    Discuss what are the build-in data type (Object) in Python
  • csci133number.py
    Document Integer, Float, Long, and Complex number
  • csci133class.py
    Some notes I have on python's class, tkinter's other module
  • csci133ifelif
    Demonstration of the uses of if and elif (else-if) keyword
  • csci133c7.py
    Classic how to clean up a string and storing the string's corresponding line numbers, it discuss the use all the things we learned so far
  • csci133c8.py
    Some notes on the python's class, and subclass too
  • csci133allCombination.py
    Example of why nest while loop is bad, and how to use one if you really must have it. Plus counter solutions.
  • csci133rep1.py
    An example of how to validate input of telephone number in a specific format, demonstrating simple use of regular expression in python.
  • csci133averageGPA.py
    Simple exercise program to calculate the grade point average
  • csci133rockPaperScissors.py
    A game of rock, paper, scissor implemented in python
  • csci133clock.py
    An example of how to make a clock with tkinter in Python
  • csci133timer.py
    A tutorial on how to build a timer with tkinter in Python

Stackoverflow Goodies


C++ Tutorial

Tuesday, May 22, 2012

Python: How to make a stop watch timer using tkinter

First thing we have to understand is how the time actually work. If you do, you can skip ahead to the next section. I was not completely sure how the time work. I confirmed from the search on google and here is what it said.

1 min = 60 seconds 1 seconds = 100 centiseconds


We use the similar code as the Clock, there is a Lable (a textbox) called timeText, and we will update it every 1 centisecond, and increment our time sturcture by 1 as well. Take a look at the way it is designed.
# timer is a list of integer, in the following order
timer = [minutes, seconds, centiseconds]
Notice in the actual code it is initialized to 0,0,0. But it then created a problem of not being show as 00:00:00 as a normal stop watch would. One way to get around this is to use the string's format.() function.
pattern = '{0:02d}:{1:02d}:{2:02d}'
timeString = pattern.format(timer[0], timer[1], timer[2])

{0:02d}, the first 0 means which parameter in the format() function call, 02d means, it is expecting an integer of length 2, the 02 means it is padding with leading zeros infront of it. Take note of this feature, as it is really powerful, you can mix and match different parameters, instead of {0} {1} {2}, you can do creative things like {2} {1} {1} {2} {0}, (such as different order, multiple use of the same varaible, etc).



The following program contains 4 buttons (start, pause, reset, quit). Which they do what they are named after respectly. The reset function work both running and paused clock. Maybe it is a good idea to add a time lap feature?

import Tkinter as tk

# Note: Python 2.6 or higher is required for .format() to work
def update_timeText():
    if (state):
        global timer
        # Every time this function is called, 
        # we will increment 1 centisecond (1/100 of a second)
        timer[2] += 1
        
        # Every 100 centisecond is equal to 1 second
        if (timer[2] >= 100):
            timer[2] = 0
            timer[1] += 1
        # Every 60 seconds is equal to 1 min
        if (timer[1] >= 60):
            timer[0] += 1
            timer[1] = 0
        # We create our time string here
        timeString = pattern.format(timer[0], timer[1], timer[2])
        # Update the timeText Label box with the current time
        timeText.configure(text=timeString)
        # Call the update_timeText() function after 1 centisecond
    root.after(10, update_timeText)

# To start the kitchen timer
def start():
    global state
    state = True

# To pause the kitchen timer
def pause():
    global state
    state = False

# To reset the timer to 00:00:00
def reset():
    global timer
    timer = [0, 0, 0]
    timeText.configure(text='00:00:00')

# To exist our program
def exist():
    root.destroy()

# Simple status flag
# False mean the timer is not running
# True means the timer is running (counting)
state = False

root = tk.Tk()
root.wm_title('Simple Kitchen Timer Example')

# Our time structure [min, sec, centsec]
timer = [0, 0, 0]
# The format is padding all the 
pattern = '{0:02d}:{1:02d}:{2:02d}'

# Create a timeText Label (a text box)
timeText = tk.Label(root, text="00:00:00", font=("Helvetica", 150))
timeText.pack()

startButton = tk.Button(root, text='Start', command=start)
startButton.pack()

pauseButton = tk.Button(root, text='Pause', command=pause)
pauseButton.pack()

resetButton = tk.Button(root, text='Reset', command=reset)
resetButton.pack()

quitButton = tk.Button(root, text='Quit', command=exist)
quitButton.pack()

update_timeText()
root.mainloop()

Python: How to make a clock in tkinter using time.strftime

This is a tutorial on how to create a clock / Timer using tkinter in Python, note you might have to change Tkinter to tkinter depending on your version of the Python you have. I am using Python 3.2 at the moment. The code itself is quite simple, the only part you need to know is how to get the current time, using time.strftime. You can also get the day of the week, the current month, etc, by changing the parameter you are supplying the function. (See the link for the full table of possible options). But yes, almost anything you can think of any use of, it is there already. :) So this can actual be developed to a calendar like GUI.

Related Tutorial with source code
Stop watch GUI (for counting time): http://ygchan.blogspot.com/2012/05/python-stop-watch-timer-source-code.html


import Tkinter as tk
import time

def update_timeText():
    # Get the current time, note you can change the format as you wish
    current = time.strftime("%H:%M:%S")
    # Update the timeText Label box with the current time
    timeText.configure(text=current)
    # Call the update_timeText() function after 1 second
    root.after(1000, update_timeText)

root = tk.Tk()
root.wm_title("Simple Clock Example")

# Create a timeText Label (a text box)
timeText = tk.Label(root, text="", font=("Helvetica", 150))
timeText.pack()
update_timeText()
root.mainloop()
Reference: http://docs.python.org/library/time.html#time.strftime
Reference: http://docs.python.org/library/string.html#formatstrings

Sunday, May 20, 2012

Python: How to load and display an image (GIF) in tkinter














Reference: http://stackoverflow.com/q/10675551/1276534
Credits: mg_, Carlos, George, Bryan Oakley

This is a simple code that get the input from the inputBox to myText, and also display a picture (gif only) to the tkinter window. Depending on what else you need to check or do, you can add more functions to it. Notice you might have to play around with the order of the line image = tk.PhotoImage(data=b64_data). Because if you put it right after b64_data = .... It will gives you error. See reference at the bottom if you want to learn more.

import tkinter as tk
import urllib.request
import base64

# Download the image using urllib
URL = "http://www.contentmanagement365.com/Content/Exhibition6/Files/369a0147-0853-4bb0-85ff-c1beda37c3db/apple_logo_50x50.gif"

u = urllib.request.urlopen(URL)
raw_data = u.read()
u.close()

b64_data = base64.encodestring(raw_data)

# The string you want to returned is somewhere outside
myText = 'empty'

def getText():
    global myText
    # You can perform check on some condition if you want to
    # If it is okay, then store the value, and exist
    myText = inputBox.get()
    print('User Entered:', myText)
    root.destroy()

root = tk.Tk()

# Just a simple title
simpleTitle = tk.Label(root)
simpleTitle['text'] = 'Please enter your input here'
simpleTitle.pack()

# The image (but in the label widget)
image = tk.PhotoImage(data=b64_data)
imageLabel = tk.Label(image=image)
imageLabel.pack()

# The entry box widget
inputBox = tk.Entry(root)
inputBox.pack()

# The button widget
button = tk.Button(root, text='Submit', command=getText)
button.pack()

tk.mainloop()


Here is the reference if you want to know more about the Tkinter Entry Widget: http://effbot.org/tkinterbook/entry.htm
Reference on how to get the image: Stackoverflow Question

Friday, May 11, 2012

Python: Rock, Paper, Scissor Game Source Code

I implemented a simple game of rock, paper, scissors game in python as a after school project. The game itself is really simple, not that I need to. But I pay a quick visit to wiki's page, and read through it. The original program has a long list of if statement, but as I was thinking through it, it comes to me quickly, that you actually does not need to have that many control statement, just three is enough. Since there is only three possible outcome.

The logic goes like this:
  1. If you and the computer's outcome (choice) is the same, then you are tie. Regardless of what kind of choice you or your computer made. A tie is a tie.
  2. Then there is 3 possible ways you can win. 
    1. You are Rock, computer is Scissors
    2. You are Paper, computer is Rock
    3. You are Scissors, computer is Paper
  3. If you didn't tie, and you didn't win, your only option is to lose the game. 
You can easily put a while (myResponse is not 'quit') loop, and have this game goes on forever. Below is the source code for the game. I found out I win quite often... for what ever reason.

# Hunter College CSCI133 Python Project
# Rock Paper Scissors Game Source code in Python
# Implemented by George Chan, 5/2/2012
# Email: ygchan89@gmail.com
# A simple game to play rock, paper, scissors with the computer

import random
# Create the list of of choices, which stored at string
gameChoices = ['rock', 'paper', 'scissors']
# Our default ready flag is false
ready = False

print('rock, paper, scissors Game!')
while (not ready):
    myResponse = raw_input('Please enter which option you are going with: ')
    myResponse = myResponse.lower()
    # We will change our flag to true and break out of the loop
    # if and only if the input is equiv to one of our choices
    if (myResponse in gameChoices):
        ready = True

# Randomly pick a choice from the list gameChoices
computerResponse = random.choice(gameChoices)
print('Computer picked:', computerResponse)

# There are three possible condition of the game, either you tie,
# with the computer or you win, else you lose
# Tie condition is when you and computer choice is the same 
if (myResponse == computerResponse):
    print('Tie Game')
# Win condition is the below three possible one
elif (myResponse == 'rock' and computerResponse == 'scissors' or
      myResponse == 'paper' and computerResponse == 'rock' or
      myResponse == 'scissors' and computerResponse == 'paper'):
    print('You win')
# If you didn't tie, didn't win, then you must lose
else:
    print('You lose!')
Sample Output:
rock, paper, scissors Game!
Please enter which option you are going with: rock
('Computer picked:', 'rock')
Tie Game

rock, paper, scissors Game!
Please enter which option you are going with: rock
('Computer picked:', 'scissors')
You win

Saturday, April 7, 2012

Python: How to insert characters to the string at the end

Reference: http://stackoverflow.com/q/10059554/1276534
Credits: user1319219, Akavall, Mark Byers

Just in case you wondering what are the ways to insert character to the string at the front or back (beginning or end) of a string. Here are the ways to do it. Notice, string is immutable object, so you can not insert anymore characters into it. All we are doing is create a new string, and assign it to the variable. (That's why I did not use the same name, because I want to emphasize they are NOT the same string). But you can just as well use text = (any method)

# Create a new string that have 1 x in the beginning, and 2 x at the end
# So I want the string to look like this 'xHello Pythonxx'
text = 'Hello Python'

# Method 1, string concatenation
new_text = 'x' + text + 'xx'

# Method 2, create a new string with math operators
i = 1
j = 2
new_text = ('x'*i) + text + ('x'*j)

# Method 3, use the string's join() method
# You are actually joining the 3 part into a originally empty string
new_text = ''.join(('x', text, 'xx'))
And in case you don't trust me and want to see the output:
xHello Pythonxx
xHello Pythonxx
xHello Pythonxx

Python: How to find the integer and float in a string

Reference: http://stackoverflow.com/a/10059001/1276534
Credits: MellowFellow, hexparrot

If you have a string from somewhere, say a textbook, or an input. The string contain the data information you need. How do you extract the string? There are quite a few way to do it, range from hard code accessing it from index, to finding the E=, to using regular expression. In this example we will go over the middle of the range one. Because as beginner, it might not be the best idea to introduce regular expression yet. Plus this is the version I understand, maybe the regular expression version will be provided soon. (If you can't wait, you can check out from the reference link from above, there is the regular expression solution as well.)
# Assume you get this string from either a file or input from user
text_string = 'The voltage is E=500V and the current is I=6.5A'

# The starting index of this locating the voltage pattern
voltage_begin = text_string.find('E=')
# The ending index, note we are ending at 'V'
voltage_end = text_string.find('V', voltage_begin)

voltage_string = text_string[voltage_begin:voltage_end]
print(voltage_string, 'is at index:', voltage_begin, voltage_end)

#Since we know about the first to index is not useful to us
voltage_string = text_string[voltage_begin+2:voltage_end]

# So since now we have the exact string we want, we can cast it to an integer
voltage_as_int = int(voltage_string)
print(voltage_as_int)

Python: How to search a list of class element by their data (self.name) variable

Reference: http://stackoverflow.com/q/10052322/1276534
Credits: nitin, kindall

Imagine you have a class of Food, and you want to create a list that store your class of Food. How do you search your class element within your list? Take a look at the code.
class Food:
    def __init__(self, name):
        self.name = name

chicken = Food('Egg')
cow = Food('Beef')
potato = Food('French Fries')

# And then you create the list of food?
myFoodList = [chicken, cow, potato]
The way you want to implement your class so you can search through them by their name variable is done via dictionary. (This is one way to do it, set also might work depend on your class's implementation and required functionality).
class Food:
    lookup = {}
    def __init__(self, name):
        self.name = name
        Food.lookup[name] = self

chicken = Food('Egg')
cow = Food('Beef')
potato = Food('French Fries')

# Example of a lookup from the dictionary
# If your name is in your class Food's lookup dictionary
if 'Egg' in Food.lookup:
    # Do something that you want
    print (Food.lookup['Egg'].name)

Friday, April 6, 2012

Python: How to remove, or pop an element randomly from a list

Reference: http://stackoverflow.com/q/10048069/1276534
Credit: Henrik, F.J, Óscar López, Niklas B.

Assuming you want to randomly remove an element from your list, you can use the random module, to generate a random number, between the valid index in your list. Take a look at the code below.
# Import the random module
import random

# This is your list with some number
# But you can of course have anything you in your list
myList = [1, 3, 5, 7, 9, 11]

# Method #1
myList.pop(random.randrange(len(myList)))

# Method #2 (This one will change your list)
random.shuffle(myList)
# While my list is not empty
while myList:
    myList.pop

(Method 1) Let's studying this code from the inner to the outer layer.
  1. We get the length of the list, with my len(myList)
  2. Then we call randrange(), what randrange does it return a number that is pick randomly between the range we provide it. But except we do not actually create this list. Like range() would.
  3. Then finally we pop it from our list.
(Method 2) This will be good, if you want to use your list all together, instead of just popping one element. This is used in the csci133 example in the playing deck, since you have to shuffle your whole deck and then pick 1 card at a time. It make sense to have it shuffled.

    Thursday, April 5, 2012

    Python: When NOT To use Global Variable, Use Return!

    Reference: http://stackoverflow.com/q/10036747/1276534
    Credit: Ricky, jdi, Maty

    Using global variable in your Python function is really easy, but today I read a post that explain why not to use it. And I found it make a lot of sense, I am not used to write without the pass by reference. Take a look at this code below.
    def getSalary():
        global a, b, c
        a = input("Please enter the boss's salary")
        b = input("Please enter the director's salary")
        c = input("Please enter the factory worker's salary")
    

    Notice this function, it asks the user for 3 different salary and store them in a, b, c respectively. But it is not a good practice, instead we should use the return function.

    def getSalary():
        a = input("Please enter the boss's salary")
        b = input("Please enter the director's salary")
        c = input("Please enter the factory worker's salary")
        return a, b, c
    
    # And to way to use this function is like
    a, b, c = getSalary()
    
    This make the code a lot more readable, and useable. Imagine if you make a mistake in the program, if you use global variable, you will have a very hard time tracking where exactly does your value get changed. While doing it the second method, you will know a, b, c is changed on the getSalary line's return. And you can print them as you writing your program to debug it.

    And as jdi pointed out, it is always always better to use more meaningful variable name than a,b,c,d, or x,y,z. Imagine you use bossSalary, directorSalary, factoryWorkerSalary, the code is a lot easier to understand. Granted, maybe a little bit long. But maybe you can use workerSalary at least!

    And when you have a function that modify your object, such as your own class, a list. Maybe (depending on the situation), you might want to create a new variable and assign it, or you can overwrite it too!
    def newSalary(salary):
        return salary + salary * 0.02
    
    # Use it like this
    nextYearSalary = newSalary(salary)
    # Or overwrite the old one
    mySalary = newSalary(salary)
    

    Tuesday, April 3, 2012

    Python: How to print the ValueError Error Message

    try:
        ...
    except ValueError as e:
        print(e)
    
    

    Python Tkinter: How to set the window size without using canvas

    Reference: http://stackoverflow.com/q/9996599/1276534
    Credit: George, Bryan Oakley

    Here is the code on how to set the window size without using canvas, it is great if you just starting, or do not want to use canvas to do this. You can specify your dimension in your frame, and then use pack_progate(0) flag to tell tkinter to use your size.
    import tkinter as tk
    
    root = tk.Tk()
    frame = tk.Frame(root, width=400, height=400)
    frame.pack_propagate(0) # set the flag to use the size
    frame.pack() # remember to pack it or else it will not be pack
    
    textBox = tk.Label(frame, text="(x,y): ")
    textBox.pack()
    
    root.mainloop()
    
    Note: If your frame is not big enough to how the items, it will expand to fit your items). And the pack_progate(0) is a flag, it does not replace pack() method, you still have to call it or otherwise it will not appear. Hope this help.

    Reference: stackoverflow 1, stackoverflow 2

    Monday, April 2, 2012

    Python: [] vs. {} vs. ()

    Reference: http://stackoverflow.com/q/4407873/1276534
    Authors: Zolomon, Greg Hewgill, Andrew Jaffe

    It is a good note post to make sure we remember what is [] vs. {} vs. ()

    () - tuple

    A tuple is a sequence of items that can't be changed (immutable).

    [] - list

    A list is a sequence of items that can be changed (mutable).

    {} - dictionary or set

    A dictionary is a list of key-value pairs, with unique keys (mutable). From Python 2.7/3.1, {} can also represent a set of unique values (mutable).

    Python: Regular Expression 101 Example Code

    Reference: http://stackoverflow.com/q/9980381/1276534
    Authors: Rajeev, George

    In computer science theory class, we learned about regular expression. But it is unclear what exactly can it do at first, today I would like to introduce data validation as an example that uses the concept of regular expression. Python itself, like other language I assume (heard), has an implementation of regular expression. It comes standard from python too, see: http://docs.python.org/library/re.html

    For example, you would like to ask the user for a telephone number, in the format of: 917-222-1234, if it is not in the format of XXX-XXX-XXXX, it will ask the user again until it is store. Let's take a look at the sample code.
    import re
    
    while True:
        # Get the user's input into the string
        myString = input('Enter your telephone number: ')
        
        # Matching it with the regular expresssion
        # isGoodTelephone will return True if it matches
        isGoodTelephone = re.match('^[0-9]{3}-[0-9]{3}-[0-9]{4}$', myString)
        
        if (isGoodTelephone):
            print('Great! Got your phone number into the system')
            print('Entry:', myString)
        else:
            print('Not in the correct format. Ex: xxx-xxx-xxxx')
        print()
    
    
    Output of the csci133rep1.py:
    Enter your telephone number: 917-123-1234
    Great! Got your phone number into the system
    Entry: 917-123-1234
    
    Enter your telephone number: 9171231234
    Not in the correct format. Ex: xxx-xxx-xxxx
    
    Actually the basic of the regular expression is not too hard to learn, take a look at the bottom and you will able to figure out how to use it with no problem. Didn't need to put too much comment to make it understandable. Although there are much more ways to use it than just the telephone.
    ^[0-9]{3}-[0-9]{3}-[0-9]{4}$
    ^       # mark the start of the telephone string
    [0-9]   # any one of the 0123456789
    {3}     # match it exactly three times, no less
    -       # a hyphen symbol
    [0-9]   # any one of the number between 0 and 9
    {3}     # exactly three copies
    -       # another hyphen symbol
    [0-0]   # any one of the number 0-9
    {4}     # four times
    $       # mark the end of the telephone string
    

    Sunday, April 1, 2012

    Python: Calculate Grade Point Average In a 4.0 Scale

    This is a simple program that take a list of grade, and then convert it to a 4.0 GPA scale with 1 decimal point, finally calculate the grade point average.
    # Take the list of grade as input, assume list is not empty
    def convertGrade(myGrades):
        myResult = [] # List that store the new grade
        for grade in myGrades:
            gpa = (grade / 20) -1
            # Depending on how many deciaml you want
            gpa = round(gpa, 1)
            myResult.append(gpa)
        return myResult
    
    # The list of grades, can be more than 5 if you want to
    grades = [88.3, 93.6, 50.2, 70.2, 80.5]
    convertedGrades = convertGrade(grades)
    print(convertedGrades)
    
    total = 0
    # If you want the average of them
    for grade in convertedGrades:
        total += grade # add each grade into the total
        
    average = total / len(convertedGrades)
    print('Average GPA is:', average)
    
    Output:
    [3.4, 3.7, 1.5, 2.5, 3.0]
    Average GPA is: 2.82
    

    Saturday, March 31, 2012

    Python: Get the most frequent elements from list when there is more than one

    Reference: stackoverflow
    Authors: james_kansas, Niklas B.

    The question is: When you are given a list that is unsorted, how do you get the most frequent appeared element, in particular, when there is more than one.
    from collections import Counter
    
    def myFunction(myDict):
        myMax = 0 # Keep track of the max frequence
        myResult = [] # A list for return
        for key in myDict:
            # Finding out the max frequence
            if myDict[key] >= myMax:
                if myDict[key] == myMax:
                    myMax = myDict[key]
                    myResult.append(key)
                # Case when it is greater than, we will delete and append
                else:
                    myMax = myDict[key]
                    del myResult[:]
                    myResult.append(key)
        return myResult
    
    foo = ['1', '1', '5', '2', '1', '6', '7', '10', '2', '2']
    print('The list:', foo)
    myCount = Counter(foo)
    print(myCount)
    
    print(myFunction(myCount))
    
    Output
    The list: ['1', '1', '5', '2', '1', '6', '7', '10', '2', '2']
    Counter({'1': 3, '2': 3, '10': 1, '5': 1, '7': 1, '6': 1})
    ['1', '2']
    
    
    More Reading: http://stackoverflow.com/questions/1518522/python-most-common-element-in-a-list

    csci133allCombination.py

    Reference: http://stackoverflow.com/q/9961077/1276534
    Authors: PePe, Li-aung Yip

    Overview: Example of this nested while loop is a bad idea, and noting the while loop in python require resetting the loop counter to be 0. And for usage of getting the combination of everything, use either nested for loop with range() function, or itertools, which takes list and return every possible combination from each element in the list you give as argument. And also, xrange() is replaced by range() at 3.0.

    In C++, although it might not be recommended, we can write a nested while loop and the following code will work. Because of unknown reason.
    a = 0
    b = 0
    c = 0
    while a <= 5:
        while b <=3:
            while c <= 8:
                print(a , b , c)
                c += 1
            b += 1
        a += 1
    
    Output is the following
    0 0 0
    0 0 1
    0 0 2
    0 0 3
    0 0 4
    0 0 5
    0 0 6
    0 0 7
    0 0 8
    
    Answer Because we need to remember to reset the loop's counter, a, b, c respectively on each iteration. But this method is kind of funky.
    a = 0
    b = 0
    c = 0
    
    while a <= 5:
        while b <=3:
            while c <= 8:
                print(a , b , c)
                c += 1
            b += 1
            c = 0 # reset
        a += 1
        b = 0 # reset
        c = 0 # reset
    
    I think most python programmer would prefer using the for loop over the range() function. It is interesting also to note and learn that, xrange() is the range() function, if you are using python 2.x. From 3.0 on, use range instead. :)
    for a in range(5+1): # Note xrange(n) produces 0,1,2...(n-1) and does not include n.
        for b in range (3+1):
            for c in range (8+1):
                print(a, b, c)
    
    But then wait... from the Li-aung Yip, there is a better way. Check out this solution which involve using itertools.product()
    import itertools
    for a, b, c in itertools.product(range(5+1), range(3+1), range(8+1)):
        print a,b,c
    For even more reading: Dan Goodger's "Code Like a Pythonista: Idiomatic Python" Thought: I think 2 second way resemble C++ the most to me, I don't know if I want to use while loop even in C++. But it is great to learn another function from the itertools, the itertools.product(). And nice to see the use for for a, b, c. I think it is powerful, but never use it in my code yet, should practice using it.
    import itertools
    
    colors = ['red', 'green', 'blue']
    vehicles = ['car', 'train', 'ship', 'boat']
    numbers = [1, 2, 3, 4, 5]
    
    """Pints out all the possible combination of number of color vehicles"""
    for color, vehicle, number in itertools.product(colors, vehicles, numbers):
        print(number, color, vehicle)
    
    
    More reference: http://docs.python.org/library/itertools.html

    Wednesday, March 28, 2012

    csci133c7.py

    or known as csci133cleanup.py

    In this tutorial we will write a program that clean up the string, it is one of the most classic program. Almost every student will be given a novel text file or input text file and ask them to do something on the data. So the first thing is to "open and load" the text file, and get the English letters into a new string. This tutorial looks long, because I included the full source code of every single program, but in fact it is only minor changes. Read on!
    # Version 1 of csci133cleanup.py
    # Full implementation of cleanup
    wordList = [] # Create a list to store our words
    abc = 'abcdefghijklmnopqrstuvwxyz'
    
    with open('novel.text') as book:
        for line in book:
            cleanline = ''
            for character in line.tolower():
                if character in abc:
                    cleanline += character
                else:
                    # Important! We have append a space!
                    cleanline += ' '
            for word in cleanline.split():
                if word not in wordList:
                    wordList.append(word)
    
    The first version we are only cleaning up the string text, so there are nothing too special about it. But notice, on line 18, we appended a space to it. Why? Take a moment to think about it, or try to clean 'Doctor--John' on a piece of paper.

    Answer: Because we need this mechanism to separate possible words, for example, here is a string Doctor--John. If we did not append a space, we will get 'DoctorJohn' in one word. When we want every single word in the file, we want to separate them instead of keeping them as the same one.
    # without space append: Doctor--John, result in DoctorJohn
    # with space append: Doctor--John, result in Doctor  John (YES!)
    
    Of course this is not without its problem, for example, we will be left with a lot of 's', so we will want to check if it is already in the list or not. (See line 16), if they are in the list, we might not want to append it again. *Depend on your need, maybe you can add a line number to it. See the next example.
    # Version 2 of csci133cleanup.py
    # Insert the line numbers into the dictionary
    wordList = {} # Create a dictionary to store them
    abc = 'abcdefghijklmnopqrstuvwxyz'
    
    with open('novel.text') as book:
        for line in book:
            lineNumber = 1 # Starting at line 1
            cleanline = ''
            for character in line.tolower():
                if character in abc:
                    cleanline += character
                else:
                    # Important! We have append a space!
                    cleanline += ' '
            for word in cleanline.split():
                if word in wordList:
                    wordList[word].append(lineNumber)
                else:
                    # Store the value as a list that contain 1 item
                    wordList[word] = [lineNumber]
            lineNumber += 1
    
    Take a moment to read and compare the code. The very first line is different. We are using a dictionary instead of list. Because when we want to check if the item is in the dictionary already or not, we want to use its build in function, instead of going them one by one. And the other difference is, we are now appending the line number into a list of them. There is an interesting part to it, See line 21.
    wordList[word] = [lineNumber]
    Notice, we can not use wordList[word] = lineNumber. Because we are creating the first value for the dictionary's key. We instead will create this value as a list that contain one integer. I actually did not aware of this when I was learning python, I keep running into error, because I only used a single interger. And when I try to append to this single integer, it does not work.

    The last version we want to search it, we want to look up our dictionary we just created. Take a look at the last couple of lines.
    # Version 3 of csci133cleanup.py
    # This version include part 1 - 3
    wordList = {}
    abc = 'abcdefghijklmnopqrstuvwxyz'
    
    with open('novel.text') as book:
        lineNumber = 1
        for line in book:
            cleanline = ''
            for character in line.tolower():
                if character in abc:
                    cleanline += character
                else:
                    cleanline += ' '
            for word in cleanline.split():
                if word in wordList:
                    # do something, such as append line number
                    wordList[word].append(lineNumber)
                else:
                    wordList[word] = [lineNumber]
            lineNumber += 1
    
    while True:
        word = input('Enter a word here: ' )
        if word in wordList:
             print('Found on lines:, wordList[word])
        else:
             print('Not found.')
    
    wordList = {'apple':[2, 25, 55, 100], 'banana':[5, 10, 36, 90]' ...}
    
    This is the first time we see a while statement in python, the structure of the while loop is simple. while (condition is true), it will execute all the code within it once, and then check if the condition is true, if it is true, do it again, if it is not, it will exist and go to the next statement. See we have 'True' as the condition, that means this loop will run forever, until we kill it with keyboard interrupt.

    Keyboard interrupt hot key: Control + C

      Tuesday, March 27, 2012

      csci133ifelif.py

      Reference: http://stackoverflow.com/questions/7052393/python-elif-or-new-if
      Today when I am reading on the python exercises, I came across one of the exercise program it uses elif (in chapter 10). For a second I am not sure what does it mean because it is called differently. But when I read closely to the source file. It looks like it is trying to replaces some of the other if else statements. Finally I look it up online, I found out it is a little bit more than just if else loops.
      def foo(var):
          # Check if var is 5
          if var == 5:
              var = 6
          elif var == 6:
              var = 8
          else:
              var = 10
          return var
      
      def bar(var):
          if var == 5:
              var = 6
          if var == 6:
              var = 8
          if var not in (5, 6):
              var = 10
          return var
      
      print foo(5) # 6
      print bar(5) # 8
      
      You can see the exam of foo(5), if the val is 5. Then the rest of them are treated as (else) loop. The elif is a nested else if loop. It is good (maybe) if you want a cleaner looking program, because you don't have the nested else if loops, the indent level is smaller, and faster compare to a sequence of if, if, if statements, because you are not checking explicitly for every single if statement. Note: always try to put the most common condition on the top, so things can check off the 'list of conditions' faster.

      For example: If you want to check if a string is English word or not, you would want to check if "isalpha()" or not, and then you start to clean up the letters. So that way, your loop will exist as soon as it knows it contain non-letter characters.