CSC111 Lab 4

From dftwiki3
Revision as of 13:05, 18 February 2010 by Thiebaut (talk | contribs) (More nested for-loops)
Jump to: navigation, search

This lab deals with Linux Commands, for-loops, and string operations.



LinuxTuxPlay.jpg

Playing with Linux

Copying Files

  • Login to beowulf with your 111c-xx account.
  • Execute the following commands at the Linux prompt:
     getcopy dummy3.py        

     backupfiles
  • It will copy the file dummy3.py from your instructor's account to your home directory, and the second line will make backup copies of your files (in case you inadvertently lose some of them during this exercise).
  • The file dummy3.py is a simple python program you will be playing with. Verify that you do have this file in your directory:


       ls -l        (that's ell ess minus ell)
The -l switch makes the ls command generate a "long" listing, with the date you last modified the files.
  • Run the dummy3.py program to verify that it works.


      python dummy3.py
  • Assume that this program is actually a program you have been developping. Let's assume that it is working just the way you want and you would like to make a copy of it to save its current state before you continue editing it. Here's how you would do it:


      cp  dummy3.py  dummy3.py.good
  • This copies dummy3.py into a new file called dummy3.py.good. Use the ls command to see that you have this new file in your directory.
  • Now edit dummy3.py, and modify it, adding errors in the code (Go ahead, don't be afraid!).
  • Try to run it with Python again. It should crash with some errors. Now, imagine that you just cannot remember what you changed in the program, and that you want to return to the last working version. Then type:
       cp dummy3.py.good dummy3.py
  • Accept to overwrite the original by typing y. Now, dump the contents of the file on the screen to see if it contains the original:
       cat dummy3.py
  • Then run it:
       python dummy3.py
  • You now have the basics for making backup copies of your files.

Deleting files

  • To delete files we use the rm (for remove) command.

Let's remove the dummy3.py program from your directory:


      rm dummy3.py
  • Check with the ls command that the file is now gone from your directory.
  • Get a new copy of it from my account with the getcopy command:


      getcopy dummy3.py
  • Do an ls to see it there. You should also see dummy3.py~ and dummy3.py.good. By the way the dummy3.py~ file is the way the file was before you last edited it with emacs. Emacs creates this file automatically and appends a ~ sign to the end.
  • Let's remove all the dummy3 files:


      rm dummy3*
  • The * (star) character in the command above is called a wild-character, and matches any word. So all the files whose name starts with dummy3 will be targeted for deletion. Verify afterward with ls that all the dummy3 files are gone.

Another Linux command

Who?

SherlocksLinux.png
  • Ever wonder who else in the class was working with python? Simple with Linux: the w command, for WHO, will tell you.
  • Go ahead and type w at the Linux prompt to find out... The right hand-side of the listing will even tell you what the users are actually doing. -bin/tcsh is the name of the program in Linux that displays the prompt to the user and executes the commands (such as ls, or cp, etc.)

Last time logged in?

  • When was the last time you logged in? Linux keeps many logs of all the activities that take place in the computer. Figuring it out is simply to know what the Linux command is. In our case it's lastlog.
  • Try it with your account number or with your instructor:
      lastlog -u 111c-xx    (replace xx by your two-letter Id)

      lastlog -u thiebaut

Python Programming

Loops

  • Could we write a Python program that will check on users for us? You bet! Create the program below, and test it out.
.

# checklog.py
# 111c-xx
#
import os
 
def main():
     Id = raw_input( "Please enter Id of student (e.g. aa) " )
     command = "111c-" + Id
     os.system( "lastlog -u " + command )       


main()

.
  • Let's figure out how to generate all the Ids automatically, with a program. Write another program that generate the list below with a for-loop:
aa
ab
ac
ad
ae
...
az 
  • Once your program works, merge it with the checklog.py program so that your program will report the login time for all the 111c-aa to 111c-az accounts.

Nested For-Loops

Let's take the generation of 111c accounts one notch up!

  • The following program prints all the distinct two-letter parts of the 111b account numbers. Run the program and observe its output.
for first in [ 'a', 'b' ]:
    for second in "abcdefghijklmnopqrstuvwxyz":
        print first+second,
    print

Note the second for-loop, and its different syntax. See how this for loop can take each letter of a string and put it in a variable (in this case the variable letter). In this case it is equivalent to

    for second in ['a','b','c','d','e','f','g','h','i','j','k','l', \
                   'm','n','o','p','q','r','s','t','u','v','w','x','y','z' ]:
       print first+second
  • Modify the program so that it also prints all the two-letter parts of the form ca, cb, cc, cd, ... cz
  • Modify the program so that it prints the accounts with "111c-" attached to them and with a line counter, as shown below:
      1 111c-aa
      2 111c-ab
      3 111c-ac
      ...
      26 111c-az
      27 111c-ba
      28 111c-bb
      29 111c-bc
      ...
      
Question 1
Modify the program so that it prints the accounts in the order shown below. You must use a double loop!
      aa ba ca
      ab bb cb
      ac bc cc
      ad bd cd
      ae be ce
      ...
      az bz cz

More nested for-loops

Store the following program in a file:

def main():
     zoo = [ "pig", "horse", "elephant" ]
     for animal in zoo:
          for i in range( len( animal ) ):
               print animal,
          print

main()
  • Before you run the program, try to figure out what it will print.
  • Run it and see if you guessed right.
  • If you didn't guess right, take a second closer look at the program and figure out why the program works that way.
Question 2
Modify the program so that it prints pig only once, horse twice, and elephant three times, as follows:
pig
horse horse
elephant elephant elephant

String Slices

  • Use Python in interactive mode and try the following Python statements. Try to figure out the answers to the questions.
Python 2.6 (r26:66714, Nov  3 2009, 17:33:38) 
[GCC 4.4.1 20090725 (Red Hat 4.4.1-2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = "H:/English103/paper1.doc"
>>> a

>>> len( a )

>>> a[0 : 2]

>>> a[3 : 13]

>>> a[-3 : -1]

>>> a[-5 : -1]

>>> a[-5 : ]                  (no, I didn't forget the second number!)

>>> a[ : 3]                   (and no again, I didn't forget the first number!)

>>> a[3 : -3]

>>> b = "C:/My Documents/paper2.htm"

You will have discovered that both a and b contain strings representing the name of files on a computer.

Question 2
What is the string slice that will return the drive information for a (i.e. 'H:')? If you replace a by b, does your statement still return the drive for b? If not, figure out a way to take the slice that works independently of the string a, or b.
Question 3
What is the slice that will return the extension only of a (i.e. doc)? If you replace a by b in your statement, do you get the extension of b? If not, figure out a way to write the slice that will work independently of the length of the file name.
Question 4
Once you have figured out the answers to Question 2, write a simple Python program that asks the user for a file name, such as the ones we used for a or b above, and that prints out the same file name back, but with the extension replaced with "txt".
Example
Filename? C:/My Documents/paper02182010.doc
C:/My Documents/paper02182010.txt