Monday, February 20, 2012

csci133c4.py

Since we downloaded a txt file, this tutorial is about opening it. Here is the code.
with open('book.txt') as book:
    # The book is a list containing all lines
    for line in book:
        # If the line contain the string 'yourselves'
        if 'yourselves' in line:
            print(line)
The first line there is a reserved python keyword with, followed by open('filename'). It is actually a path name between the (), but if you don't provide a path, it is assumed it is the current directory. In case you have to access a file from a different folder, you would provide it a path with the file name. Such as ../../csci133/ch1/csci133c4.py.

You would open the text file into another object . You don't have to call it book, you can call it anything you want, that would be list containing all the "lines". In the event of it is actually a text file with strings after strings, you does make sense to call it something along the line of data, book, and myFile. You can try to iterate through it with for loop.
for object in objects:
    # do something here
Example problem #1: Count the number of words contained in the txt file
count = 0
with open('book.txt') as book:
    for line in book:
            # += is the same as count = count + count
            count += len(line.split())
print('There are', count, 'of words.')
Before we are done, there is also way to get input from the user, you would set up a variable, and assign it the value of the input.
Example problem #2: Take an input from the user (like cin in C++)
name = input('What is your name?')
print('Hello, nice to meet you', name) 
Python's list comprehension
It is a handy way to write code in a very short way, compare the two code. They do the same thing. I heard from people, it is a way to pretend to be smart, on the other hand, it seems useful to write code in a short way I guess. I prefer slightly the longer way, but I have a feeling in the professional world, everyone use list comprehension. Because it is faster, and less likely to create errors.
for number in numbers:
    data[number] = data[years][time] 
    return data
the data to be changed for object in objects
return [data[number][time] for number in years]
# Regular code
iceCreams = IceCreamFlavor()
iceCreamMenu = [] # iceCreamMenu is a list
for number in range(5):
    iceCreamMenu = iceCreams.random()

# Same code with list comprehension
iceCreams = IceCreamFlavor()
iceCreamMenu = [iceCreams.random() for number in range(5)]
The more I use it, the more I think it is useful. Just like all functions and methods (well, most of them). It is meant to help us write program faster and easier. Just like a a lot of the helper function is build in, this is build in to help us not have to spend as much time to get what we want.

Notice the range(5)? That means it is created a list of 5 numbers, [1, 2, 3, 4, 5]. Useful tool as well! Instead of doing a = [1, 2, 3, 4, 5]. And for number in a.
# The range(5)
for number in range(5):
    # Statement

# Same as this
numbers = [0, 1, 2, 3, 4]
for number in numbers:
    # Statement
Reference: http://docs.python.org/library/functions.html#range
range([start], stop[, step]) 
It is very commonly used in for loops, the start and stop arguments must be integers, if you didn't give it a step argument, it will be default to 1. If you didn't give it a start argument, it will be default to 0.
The range() function create a list with the number 0, 1, 2, 3, 4. Notice python is zero based, so if you need to print out from 1 to 5. You would not want to offset the number variable. <Correct way: to use the start argument>
# To print 1-5 the correct way
for number in range(1,6):
    print(number)
Output:
>>> for number in range(1,6):
...     print(number)
... 
1
2
3
4
5
>>>  
As for the step argument, it is what the increment is used. If you use the step of 2. Ex: range(0, 10, 2), it will give you [2, 4, 6, 8, 10]

Practice Problem:
# Write a range(start, stop, step) that generate the following results
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[0, 2, 4, 6, 8, 10]
[1, 3, 5, 7, 9, 11]
[0, 50, 100]
[3, 9, 12, 15, 18, 21]

Answer to the problems: Notice for the question when it ask you where to stop, you can either stop at the next value (11) for the case of 10, or stop at the next increment value, 150 for the case of 100, or 101 for the case of 100. It will still work the same. I just like to do it this way, if you get the same answer, then you should be good to go.
>>> for number in range(10):
>>> for number in range(1, 11):
>>> for number in range(0, 12, 2):
>>> for number in range(1, 13, 2):
>>> for number in range(0, 150, 50):
>>> for number in range(3, 23, 3):
Note: Because reading again on the range() documentation, I thought the only way to do print 1-5 is to offset. Which show us how important and good it is to read the reference.

Monday, February 6, 2012

csci133c3.py

Welcome to the 3rd notes for the python programming lab. Let's take a look at the code and see what does it do. Today we will talk about the function. Function is a block of code that do varies kind of thing, and might or might not return the value it get.
line = 'This is a sample line of text.'
# Measure the length of the line string
print(len(line))

# Split the line string by spaces, return a list
print(line.split())

# Measure how many word are there now
print(len(line.split()))
Output:
30
['This', 'is', 'a', 'sample', 'line', 'of', 'text.']
7
Pay close attention to line #3, when we call a function (or to use a function). We can also pass some data if the function accept it, that data is called parameter, or argument. So we passed the line into the length function, len(line). And the function returned the result of 30, and then it is being passed to the print function and print on the screen. That is why it is outputed as 30.

Whenever we want to print thing on the screen, we are always actually calling the print function, and passing the number, letter, or word into the function. What about the split function? What does it do? From the python's web manual.
http://docs.python.org/library/stdtypes.html#str.split
str.split([sep[, maxsplit]])

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified, then there is no limit on the number of splits (all possible splits are made).

For example, ' 1 2 3 '.split() returns ['1', '2', '3'], and ' 1 2 3 '.split(None, 1) returns ['1', '2 3 '].
The function require a string to be invoked on, that's why it has str.split(), the split function actually takes argument. But at the moment we just want it to split with blanks, or spaces. Note each data type has their own set of functions build in to them.

Example Problem #1: Turn a string into all lower case
If you want to turn a string to lower case
word = 'THE QUEEN'
word = 'THE APPLE'
newWord = word.lower()
print('Before:', word)
print('After:', newWord)
Output:
Before: THE QUEEN
After: the queen
Example Problem #2: Turn every word into lower case, remove the symbols, print them one by one. (One on each line). String is from a random novel on the web.
line = 'http://www.gutenberg.org/cache/epub/39133/pg39133.txt'
newLine = ''
for char in line:
    if char in 'abcdefghijklmnopqrstuvwxyz':
        newLine = newLine + char
    else:
        newLine = newLine + ' '
print('Before:', line)
print('After:', newLine)
print('Split it:', newLine.split())
for word in newLine.split():
    print(word)
Output:
Before: http://www.gutenberg.org/cache/epub/39133/pg39133.txt
After: http   www gutenberg org cache epub       pg      txt
Split it: ['http', 'www', 'gutenberg', 'org', 'cache', 'epub', 'pg', 'txt']
http
www
gutenberg
org
cache
epub
pg
txt 
So before we go, let's go to this link, download the file into our current dir. Because the next tutorial we will use that file! http://www.gutenberg.org/cache/epub/39133/pg39133.txt , and rename it to book.txt

Practice Problem:  Write a program to clean up the following string, turn all letters into lower case, and print one word per line.
foo = '[_He approaches Fabiani._]'
Output:
he
approaches
fabiani

Wednesday, February 1, 2012

Pydev in Eclipse on Mac

When you downloaded Pydev for Eclipse, you have to set up the Python interpreter before you can start using it. Here is the instruction.

To configure a Python or Jython interpreter in 
Eclipse > Preferences > PyDev



When you are in Preferences, find PyDev, and click on the Interpreter - Python



Choose New in the upper right and enter /usr/bin/python
Eclipse will then take care of the rest for you – ie. updating the $PYTHONPATH
    Reference & Credit: On Using Pydev on a Mac.