CSC111 Lab 9

From CSclasswiki
Jump to: navigation, search

--Thiebaut 01:44, 7 April 2009 (UTC)

Login/logout to Linux Account

On Windows PC in Seelye, click on Start and then click on the icon labeled Secure Shell Client, or SSH Client. On some computers it is in the first menu that pops up, on others it hides in the utilities menu.

Click on Connect and enter the following information:

If the Quick Connect window is not greeting you, click on the Quick Connect icon to get it:

  • Enter as the host name,
  • 111b-xx as your user name (change the xx to reflect your 2-letter Id)
  • Click on the Connect button
  • Enter your password, and click "Connect".

If everything goes well, you should see this:

SSH Secure Shell 3.1.0 (Build 235)
Copyright (c) 2000-2001 SSH Communications Security Corp -

This copy of SSH Secure Shell is a non-commercial version.
This version does not include PKI and PKCS #11 functionality.

Followed by the prompt:

[111b-xx@beowulf ~]$

This may be a good time to change your password to something you will more easily remember. Use the command

 [111b-xx@beowulf ~]$   passwd

To change your password.

Keep your account and password information in a safe place, or learn both by heart! You will need them every time you need to use your account and work on your homework assignment or lab.

You may want to log out now, to practice this login procedure a couple times. If you are working with a lab partner, it is a good time to log out and let her/him try the procedure.

Playing with the Emacs Editor

Execute this command from the Linux prompt:

           [111b-xx@beowulf ~]$   getcopy  .emacs

(That is "getcopy" space dot "emacs"). When it asks you if you want to overwrite the one that already is in your account, type y for YES!

This will install a configuration file that will allow emacs to understand the backspace key correctly. You only need to do this once and you will be set for the semester.

You will now get a copy of a file from your instructor's account, and edit it. The file is called Fulghum and is a short story from Robert Fulghum's book All I really need to know I learned in Kindergarten.

To get a copy of this file, type

           [111b-xx@beowulf ~]$   getcopy fulghum

followed by the return key. Then edit the file with the command

            [111b-xx@beowulf ~]$   emacs fulghum

Simply work on the first paragraph of the file, and try to straighten it up. I have indicated below, on the right-hand side, which emacs commands you can use to fix the text on your screen.

CSC111 Fulghum.jpg

When you are done with the modification, or if you want to stop for right now and save your modifications, type C-x C-c, and press y when emacs asks if you want to save the file.

Below is a summary of some useful emacs commands.

You should find some time this week to go to a lab and read the Emacs at Smith handout while in front of the terminal, on your own. This is the best way to test and learn the different features of the editor!

     DEL/Shift Backspace	Delete previous character
     c-d 	Delete character at cursor
     Esc-d 	Delete word
     c-k 	Kill line
     c-a 	Go to beginning of line
     c-e 	Go to end of line
     c-f 	Move cursor 1 character forward
     c-b 	Move cursor 1 character backward
     c-p 	Move to previous line
     c-n 	Move to next line
     c-x c-c 	quit emacs and save file
     c-x c-s 	save file but remain in emacs
     c-g 	GE OUT OF TROUBLE!

If you wonder what the remainder of the story is like, you can find it here.

Creating a Python Program with Emacs

Make sure you have exited emacs and that you see the prompt on your terminal screen.

Let's create a program.

   [111b-xx@beowulf ~]$   emacs

Type the following line into the emacs window:

# 111b-xx
# firstname lastname
# prompts the user for first and last name, along with year of birth
# outputs approximate age

fname        = raw_input( "what is your first name? " )
lname        = raw_input( "what is your last name? " )
yearOfBirth = input( "What year were you born? " )

print "Hello", fname, lname
print "you must be about", 2009 - yearOfBirth, "years old"

Note that if you want to obtain text from the user, you use raw_input, but if you want to get numbers, you use input.

Once you're done, exit emacs and run your program:

    [111b-xx@beowulf ~]$  python

Verify that the program works and gives you correct information.

Modify your program so that instead of asking for the year of birth, the program asks for your age, and then outputs what year you were born in.

The Console Mode

Just as JES had a console window, you can also test python constructs in the Python Console.

To open the console, make sure you are at the Linux prompt, and type

  [111b-xx@beowulf ~]$   python

And you will be at the console prompt.

  Python 2.5.1 (r251:54863, Jun 15 2008, 18:24:51) 
  [GCC 4.3.0 20080428 (Red Hat 4.3.0-8)] on linux2
  Type "help", "copyright", "credits" or "license" for more information.

You can enter commands directly in the console, the exact same way you were in JES. To exit of the console, just type CONTROL D.

Stay in the console and continue with the lab!

The key to processing text in Python

This is the main ways to process text and transform strings into smaller elements in Python. We'll use these methods over and over... Keep the diagram in the back of your head! :-)


Main reference

When figuring out what string method to use, make sure you check this page for a list of all string operations.

Strings are Lists of Characters

Strings are list of characters. You can search them, cut them, split them, do all kinds of operations on them.

To see some of these operations directly, start python in console mode and type these commands

    >>> line = "9.0 The Godfather: Part II (1974)"

As you type the different commands, try to understand how they work.

    >>> line[0]
    >>> line[1]
    >>> line[2]
    >>> line[-1]
    >>> line[-2]
    >>> line[0:10]
    >>> line[-5:-1]
    >>> line[-5:]
    >>> line[:10]
    >>> line.find( '(' )
    >>> index1 = line.find( '(' )
    >>> index1
    >>> index2 = line.find( ')' )
    >>> index2
    >>> line[index1:index2]
    >>> line.find( "." )
    >>> index3 = line.find( "." )
    >>> word = line[index3:index3]
    >>> print word
    >>> message = "    hello there          "
    >>> message = message.strip()
    >>> print message

Exercise 1

Find a way of printing just the year included in the "Godfather" string by taking the right slice of string ([:]). Do not use numbers! Use variables that are set to the right index using the line.find() function.

Your code should work even if we change the string.

Try your code on this line and verify that it gets the year as well:

    >>> line = "9.1 The Shawshank Redemption (1994)"
Note: You can find the list of the top 250 movies of all times at

Exercise 2

Same idea, but make your code find and print just the name of the movie.

Remove extra spaces at the front and end of the string with the strip() function.

Exercise 3

Figure out a way to extract the score (first number of the line) from the string, and print it.

Once your code works, change the string line to the following value:

  line = "           8.8 Casablanca (1942)"

Does your code work, untouched, on the new string?

Verify that your program (or collection of commands) does the job and isolate the score (without extra spaces)!

Exercise 4

Move back to the Linux prompt, and use emacs to start editing a new program.

   [111b-xx@beowulf ~]$ emacs

Enter and complete the program below so that the function getInfo() takes as input the movie line, and returns three variables containing the score, the title, and the year.


movie1 = " 9.1 The Shawshank Redemption (1994) "

def getInfo( movie ):
    # enter your code below
    score = ...

    title = ...

    year = ...

    # when you're done, return the 3 quantities
    return score, title, year
def main():

    scr, ti, yr = getInfo( movie1 )
    print "score = ", scr
    print "title = ", ti
    print "year  = ", yr


Splitting text lines into words

Return to the console mode, and test the following statements.

 >>> movie = "8.6 Dr. Strangelove or: How I Learned to Stop Worrying and Love the Bomb (1964)"
 >>> words = movie.split()
 >>> words
 >>> '-' . join( words )
 >>> ', ' . join( words )
 >>> words.sort()
 >>> '\t' . join( words )

(\t represents the tab character)

 >>> '\n' . join( words )

(\n represents the return character)

Exercise 5

Same as Exercise 4, but use the list of words contained in the movie string to generate the score, title, and year.

List of pairs

Back in console mode!

Enter and test the following statements, one after the other, and see how we can use list of pairs (or triplets, or quadruplets) with Python:

 >>> List = [ ('a', 1), ('z', 2), ('d', 10), ('k',3) ]
 >>> for ( letter, number ) in List:
 ...          print letter, number
 >>> for pair in List:
  ...         print pair[0], pair[1]

Notice that the two loops should give identical results.

Continue on...

 >>>    for ( letter, number ) in List:
   ...              print number
 >>>   List.sort()
 >>>   for ( letter, number ) in List:
 ...                print letter, number

You will have noticed that the last loops prints the pairs of letters and numbers in alphabetical order. What if we wanted them listed in increasing numerical order? The answer is that we cannot do that directly. Instead, we can create a new list of pairs, where the number is the first element of the pair, and then sort the newList before printing it:

 >>>  newList = []
 >>>  for ( letter, number ) in List:
 ...           newList.append(  ( number, letter ) )
 >>>  newList.sort()
 >>>  for pair in newList:
 ...           print pair[0], pair[1]

We could have written the last loop a different way:

 >>> for ( num, let ) in newList:
 ...           print num, let

Exercise 6: Fast/Slow animals

Get a copy of

  [111b-xx@beowulf ~]$  getcopy

Run the program. Observe that it outputs animal names prefixed with their top recorded speed.

  • Question 1: modify your program so that it displays the animals in sorted order of speed, slowest first. If you're not sure how to do it, just try to sort the list and see what happens...
  • Question 2: modify your program so that it displays the animals in sorted order of speed, fastest first. (Hints, you can use the reverse() method to reverse the order of a list)
  • Question 3: modify your program so that it displays the 10 slowest animals. (Hints: use range(10) in your for-loop)
  • Question 4: modify your program so that it displays the 10 fastest animals.
  • Question 5 (challenging!): modify your program so that it displays the animals sorted in alphabetical order. Your program should display the speed of each animal as well. (Hints: you have two ways about it: either create the initial list as a list of pairs where the animal is first in the pair, or create a second list of pairs from the first one, but each pair will be animal first, speed second)

You are now ready for Homework #9!