Difference between revisions of "CSC111 Lab 4 2011"

From dftwiki3
Jump to: navigation, search
(Playing with Linux)
 
(19 intermediate revisions by the same user not shown)
Line 11: Line 11:
 
[[Image:LinuxTuxPlay.jpg | right | 150px]]
 
[[Image:LinuxTuxPlay.jpg | right | 150px]]
 
==Playing with Linux==
 
==Playing with Linux==
 
+
(Check this [http://en.wikipedia.org/wiki/Tux page] out to figure why penguins have appeared in this lab...)
 +
 
===Copying Files===
 
===Copying Files===
 
* Login to beowulf with your '''111a-xx''' account.
 
* Login to beowulf with your '''111a-xx''' account.
Line 88: Line 89:
  
 
* 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.)
 
* 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.)
 +
 +
<br />
 +
<br />
 +
<br />
  
 
===Last time logged in?===
 
===Last time logged in?===
Line 98: Line 103:
 
   
 
   
 
       lastlog -u thiebaut
 
       lastlog -u thiebaut
 +
 +
<br />
 +
<br />
 +
<center>
 +
[[Image:PythonLogo.jpg|100px]]
 +
</center>
 +
<br />
  
 
==Python Programming==
 
==Python Programming==
  
 
===Loops===
 
===Loops===
 +
 +
====Printing the alphabet with the '''range()''' function====
 +
* Somebody in class suggested that there should be a way to print the alphabet using the range function.  The answer is YES!
 +
All you need is the '''chr()''' and '''ord()''' function.
 +
** chr( ''n'' ), where ''n'' is an integer, returns the character whose internal computer code is ''n''
 +
** ord( ''ch'' ), where ''ch'' is a character, returns the internal code of a given character
 +
**Example:
 +
<br />
 +
<source lang="python">
 +
for i in range( 65, 65+26 ):
 +
    ch = chr( i )
 +
    print( ch )
 +
 +
print()
 +
 +
for i in range( ord('a'), ord('a')+26 ):
 +
    ch = chr( i )
 +
    print( ch )
 +
   
 +
</source>
 +
<br />
 +
 +
====Python + Linux====
 +
 
* Could we write a Python program that would user the '''lastlog''' command and automatically check on all the users for us?  You bet!  Let's see how we can do so.   
 
* Could we write a Python program that would user the '''lastlog''' command and automatically check on all the users for us?  You bet!  Let's see how we can do so.   
  
Line 138: Line 174:
  
 
* Once your program works, merge it with the '''checklog.py''' program so that your program will report the login time for all the 111a-aa to 111a-az accounts.
 
* Once your program works, merge it with the '''checklog.py''' program so that your program will report the login time for all the 111a-aa to 111a-az accounts.
 +
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
 +
<center>
 +
<font color="magenta">You may switch to IDLE if you find it more comfortable to work with</font>
 +
</center>
 +
<br />
 +
<br />
 +
<br />
 +
<br />
  
 
===Nested For-Loops===
 
===Nested For-Loops===
Line 148: Line 197:
 
for first in [ 'a', 'b' ]:
 
for first in [ 'a', 'b' ]:
 
     for second in "abcdefghijklmnopqrstuvwxyz":
 
     for second in "abcdefghijklmnopqrstuvwxyz":
         print first+second,
+
         print( first+second, end=' ' )  # quote space quote
     print
+
     print()
 
</pre></code>
 
</pre></code>
  
Line 157: Line 206:
 
     for second in ['a','b','c','d','e','f','g','h','i','j','k','l', \
 
     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' ]:
 
                   'm','n','o','p','q','r','s','t','u','v','w','x','y','z' ]:
       print first+second
+
       print( first+second )
 
</pre></code>
 
</pre></code>
 
[[Image:onion.jpg| right|100px]]
 
[[Image:onion.jpg| right|100px]]
Line 179: Line 228:
  
  
;Question 1
+
 
: Modify the program so that it prints the accounts in the order shown below. You must use a double loop!
+
{| style="width:100%; background:silver"
 +
|-
 +
|
 +
 
 +
===Mini Challenge===
 +
|}
 +
[[Image:QuestionMark1.jpg|right|120px]]
 +
Modify the program so that it prints the accounts in the order shown below. You must use a double loop!
  
 
       aa ba ca
 
       aa ba ca
Line 199: Line 255:
 
     for animal in zoo:
 
     for animal in zoo:
 
           for i in range( len( animal ) ):
 
           for i in range( len( animal ) ):
               print animal,
+
               print( animal, end=" " )  # that's a space between quotes
           print
+
           print()
  
 
main()
 
main()
 
</source>
 
</source>
 
* Before you run the program, try to figure out what it will print.
 
* Before you run the program, try to figure out what it will print.
 +
* Think...
 +
* Think some more...
 
* Run it and see if you guessed right.
 
* 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.
 
* 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:
+
<br />
 +
<br />
 +
<br />
 +
<br />
 +
 
 +
 
 +
{| style="width:100%; background:silver"
 +
|-
 +
|
 +
===Challenge 2===
 +
|}
 +
[[Image:QuestionMark10.jpg|right|120px]]
 +
Modify the program so that it prints pig only once, horse twice, and elephant three times, as follows:
  
 
  pig
 
  pig
Line 214: Line 284:
 
  elephant elephant elephant
 
  elephant elephant elephant
  
;Question 3
+
 
: Write a program that uses for-loops and that prints the following list of strings:
+
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
 
 +
{| style="width:100%; background:silver"
 +
|-
 +
|
 +
 
 +
===Challenge 3===
 +
|}
 +
[[Image:QuestionMark3.jpg|right|120px]]
 +
 
 +
* Write a program that uses '''nested''' for-loops and that prints the following list of strings:
 +
 
 +
 
 
  spring 2010
 
  spring 2010
 
  fall 2010
 
  fall 2010
Line 224: Line 312:
 
  spring 2013
 
  spring 2013
 
  fall 2013
 
  fall 2013
 +
 +
* Can you use the range function to generate the years?
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
 +
===Nested-Loops and multiplication tables===
 +
 +
* Try these nested loops in a new program:
 +
 +
<source lang="python">
 +
def main():
 +
  for i in range( 10 ):
 +
      for j in range( 10 ):
 +
          print( '(', i, "," , j, ') ', sep="", end="" )  # no space between the double quotes
 +
      print()
 +
 +
main()
 +
</source>
 +
<br />
 +
<br />
 +
<br />
 +
 +
* Before running your program try to guess its output...
 +
 +
* Now modify the loops slightly:
 +
 +
<source lang="python">
 +
 +
  for i in range( 10 ):
 +
      for j in range( i, 10 ):
 +
          print( '(', i, "," , j, ') ', sep="", end="" )  # no space between the double quotes
 +
      print()
 +
 +
</source>
 +
 +
* Same exercise.  Guess, run, try to understand the logic...
 +
 +
* More modifications:
 +
 +
<source lang="python">
 +
 +
  for i in range( 10 ):
 +
      for j in range( i ):
 +
          print( '(', i, "," , j, ') ', sep="", end="" )  # no space between the double quotes
 +
      print()
 +
 +
</source>
 +
 +
 +
<br />
 +
<br />
 +
<br />
 +
{| style="width:100%; background:silver"
 +
|-
 +
|
 +
 +
===Challenge 4===
 +
|}
 +
[[Image:QuestionMark4.jpg|right|120px]]
 +
Can you write a program that uses nested for-i and a for-j loops as above and that display the multiplication table below:
 +
 +
 +
  1  2  3  4  5  6  7  8  9
 +
  2  4  6  8 10 12 14 16 18
 +
  3  6  9 12 15 18 21 24 27
 +
  4  8 12 16 20 24 28 32 36
 +
  5 10 15 20 25 30 35 40 45
 +
  6 12 18 24 30 36 42 48 54
 +
  7 14 21 28 35 42 49 56 63
 +
  8 16 24 32 40 48 56 64 72
 +
  9 18 27 36 45 54 63 72 81          ''(Don't worry if your numbers do not align as well as shown here at first...)''
 +
 +
:Note that each number at the intersection of a row and a column is the product of the top number in the column and left-most number in that row.
 +
<br />
 +
<br />
 +
<br />
 +
{| style="width:100%; background:silver"
 +
|-
 +
|
 +
 +
===Challenge 5===
 +
|}
 +
[[Image:QuestionMark5.jpg|right|120px]]
 +
Can you make your program generate this table instead?
 +
 +
 +
 +
  1
 +
  2  4
 +
  3  6  9
 +
  4  8 12 16
 +
  5 10 15 20 25
 +
  6 12 18 24 30 36
 +
  7 14 21 28 35 42 49
 +
  8 16 24 32 40 48 56 64
 +
  9 18 27 36 45 54 63 72 81      ''(Don't worry if your numbers do not align as well as shown here at first...)''
 +
 +
<br />
 +
<br />
 +
<br />
 +
{| style="width:100%; background:silver"
 +
|-
 +
|
 +
 +
===Challenge 6===
 +
|}
 +
[[Image:QuestionMark6.jpg|right|120px]]
 +
Read the documentation from this page on the '''percent operator''': [http://infohost.nmt.edu/tcc/help/pubs/lang/pytut/str-format.html infohost.nmt.edu] and see how you can use % in a string to force numbers to print in a fixed number of spaces.  Read the whole page, and pay special attention to where they print 42 and 505.  This is the way I would like you to use in your print statement to make your output look "squarre".
 +
<br />
 +
 +
<br />
 +
 +
<br />
 +
 +
<br />
 +
You are done with the lab.  Feel free to start working on [[CSC111_Homework_3_2011| Homework #3]]!
 +
<br />
 +
 +
<br />
 +
 +
<br />
 +
 +
<br />
 +
[[Category:Python]][[Category:CSC111]][[Category:Labs]]

Latest revision as of 16:08, 29 September 2011

--D. Thiebaut 09:19, 28 September 2011 (EDT)


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



LinuxTuxPlay.jpg

Playing with Linux

(Check this page out to figure why penguins have appeared in this lab...)

Copying Files

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

     backupfiles     (don't worry about the error message about backup not copying over itself...)
  • 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.


      python3 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:
       python3 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 that it is back. 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.


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 111a-xx    (replace xx by your two-letter Id)

      lastlog -u thiebaut



PythonLogo.jpg


Python Programming

Loops

Printing the alphabet with the range() function

  • Somebody in class suggested that there should be a way to print the alphabet using the range function. The answer is YES!

All you need is the chr() and ord() function.

    • chr( n ), where n is an integer, returns the character whose internal computer code is n
    • ord( ch ), where ch is a character, returns the internal code of a given character
    • Example:


for i in range( 65, 65+26 ):
    ch = chr( i )
    print( ch )

print()

for i in range( ord('a'), ord('a')+26 ):
    ch = chr( i )
    print( ch )


Python + Linux

  • Could we write a Python program that would user the lastlog command and automatically check on all the users for us? You bet! Let's see how we can do so.
  • Create the program below, and test it out.
.

# checklog.py
# 111a-xx
#
import os
 
def main():
     Id = input( "Please enter the two-letter Id of student (e.g. aa) " )
     user = "111a-" + Id
     os.system( "lastlog -u " + user )       


main()

.
  • See how Python integrates with the operating system?
  • 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 111a-aa to 111a-az accounts.





You may switch to IDLE if you find it more comfortable to work with





Nested For-Loops

Let's take the generation of 111a 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, end=' ' )  # quote space quote
    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 )
Onion.jpg
  • Modify the program so that it also prints all the two-letter parts of the form ca, cb, cc, cd, ... cz
  • Modify the program some more (see we're using the "onion" approach to programming, one new simple layer at a time!) so that it prints the accounts with "111a-" attached to them and with a line counter, as shown below:
      1 111a-aa
      2 111a-ab
      3 111a-ac
      ...
      26 111a-az
      27 111a-ba
      28 111a-bb
      29 111a-bc
      ...
      52 111a-bz
      53 111a-ca
      54 111a-cb
      ...


Mini Challenge

QuestionMark1.jpg

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, end=" " )  # that's a space between quotes
          print()

main()
  • Before you run the program, try to figure out what it will print.
  • Think...
  • Think some more...
  • 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.






Challenge 2

QuestionMark10.jpg

Modify the program so that it prints pig only once, horse twice, and elephant three times, as follows:

pig
horse horse
elephant elephant elephant









Challenge 3

QuestionMark3.jpg
  • Write a program that uses nested for-loops and that prints the following list of strings:


spring 2010
fall 2010
spring 2011
fall 2011
spring 2012
fall 2012
spring 2013
fall 2013
  • Can you use the range function to generate the years?





Nested-Loops and multiplication tables

  • Try these nested loops in a new program:
def main():
   for i in range( 10 ):
      for j in range( 10 ):
          print( '(', i, "," , j, ') ', sep="", end="" )  # no space between the double quotes
      print()

main()




  • Before running your program try to guess its output...
  • Now modify the loops slightly:
   for i in range( 10 ):
      for j in range( i, 10 ):
          print( '(', i, "," , j, ') ', sep="", end="" )  # no space between the double quotes
      print()
  • Same exercise. Guess, run, try to understand the logic...
  • More modifications:
   for i in range( 10 ):
      for j in range( i ):
          print( '(', i, "," , j, ') ', sep="", end="" )  # no space between the double quotes
      print()





Challenge 4

QuestionMark4.jpg

Can you write a program that uses nested for-i and a for-j loops as above and that display the multiplication table below:


 1  2  3  4  5  6  7  8  9
 2  4  6  8 10 12 14 16 18
 3  6  9 12 15 18 21 24 27
 4  8 12 16 20 24 28 32 36
 5 10 15 20 25 30 35 40 45
 6 12 18 24 30 36 42 48 54
 7 14 21 28 35 42 49 56 63
 8 16 24 32 40 48 56 64 72
 9 18 27 36 45 54 63 72 81          (Don't worry if your numbers do not align as well as shown here at first...)
Note that each number at the intersection of a row and a column is the product of the top number in the column and left-most number in that row.




Challenge 5

QuestionMark5.jpg

Can you make your program generate this table instead?


 1
 2  4
 3  6  9
 4  8 12 16
 5 10 15 20 25
 6 12 18 24 30 36
 7 14 21 28 35 42 49
 8 16 24 32 40 48 56 64
 9 18 27 36 45 54 63 72 81      (Don't worry if your numbers do not align as well as shown here at first...)




Challenge 6

QuestionMark6.jpg

Read the documentation from this page on the percent operator: infohost.nmt.edu and see how you can use % in a string to force numbers to print in a fixed number of spaces. Read the whole page, and pay special attention to where they print 42 and 505. This is the way I would like you to use in your print statement to make your output look "squarre".




You are done with the lab. Feel free to start working on Homework #3!