CSC111 Lab 6

From dftwiki3
Revision as of 11:50, 3 March 2010 by Thiebaut (talk | contribs) (Graphics and Chessboards)
Jump to: navigation, search

This lab is under construction...





More String Methods

PythonYellowLogo.png
We have already seen several of these methods. This lab is to reinforce our knowledge of strings.

The methods are all documented at this page: http://docs.python.org/lib/string-methods.html. Open this page and refer to it while you are working on this lab.

Use emacs or the python interactive prompt to test out different methods, as we did in class yesterday.

center()

One of the string methods is the center function.

Use it to center the title "computer SCIENCE 111" between two lines of 45 dashes. Use a variable called myTitle to store the string.

        myTitle = "computer SCIENCE 111"
        print 45*"-"
        print myTitle.center( 45 )
        print 45*"-"

capitalize()

Instead of printing the variable myTitle, print myTitle.capitalize( ) and see what happens.

upper()

Use upper() instead of capitalize(). Observe the new output.

title()

Same exercise, but with the title() method.


Programming Question 1
Write some Python code that will ask for your name, then your last name, and will print both of them centered between two lines of 60 dashes. Make your program capitalize the first letter of each word.
Example
your first name? alexAndra
your last name?  SMITH

------------------------------------------------------------
                      Alexandra Smith                       
------------------------------------------------------------

Replacing substrings in a string

To replace a substring of a string (or a word in a sentence), all you need to do is to use the replace() method.

   sentence = """Strength is the capacity to break a chocolate 
              bar into four pieces with your bare hands - and 
              then eat just one of the pieces"""

   print sentence
   sentence = sentence.replace( "chocolate", "carrot" )
   print sentence

Try it and replace the word "piece" by the word "chunk" in the same sentence, so that now you're breaking carrots into chunks.

Multiple Replacements

We are still dealing with the sentence above, but we want to replace four separate words by four new words. The words we want to replace are in this list:

  toBeReplaced = ["chocolate", "piece", "hand", "break"] 

and the replacement words are in this list:

  newWords = ["carrot", "chunk", "elbow", "melt"]

Write python statements that will take the string sentence and replace chocolate by carrot, then it will look for piece and replace it by chunk, hand by elbow, and break by melt.

Use a for-loop!

Count()

Read the documentation on the method count() and write some statements that output the number of times the word "piece" appears in sentence using the count() method.

Strip()

Read the documentation about the method strip() and use it to allow you to print the lines below left aligned.

   listOfStrings = [ "          But then, shall I never get any older than I am now?      ",
                           "     That'll be a comfort, one way -- never to be an old woman --          ",
                           "          but then -- always to have lessons to learn!           ",
                           "    Alice    " ]

Splitting strings

First, read the documentation on the split() method.

Let's use the same string as before.

   sentence = """Strength is the capacity to break a chocolate 
              bar into four pieces with your bare hands - and
              then eat just one of the pieces"""

And process it that way

   list1 = sentence.split( "\n" )
   print "list1 = ", list1

   list2 = sentence.split( )
   print "list2 = ", list2

   list3 = sentence.split( 's' )
   print "list3 = ", list3
Programming Question 2
Make your program print the number of words in sentence (there are several ways to do that: one long, one very short).
Programming Question 3
Make your program display the first and last words of the sentence.
Programming Question 4
Assume that you have a string of this type:
   NYTBestSellers = """1. THE HELP, by Kathryn Stockett
                                2. WORST CASE, by James Patterson and Michael Ledwidge
                                3. THE LOST SYMBOL, by Dan Brown
                                4. POOR LITTLE BITCH GIRL, by Jackie Collins
                                5. WINTER GARDEN, by Kristin Hannah """
Write the code that will take this string, process it, and output the information in a different format, shown below:
  Kathryn Stockett                                     The Help
  James Patterson and Michael Ledwidge                 Worst Case
  Dan Brown                                            The Lost Symbol
  Jackie Collins                                       Poor Little Bitch Girl
  Kristin Hannah                                       Winter Garden

For this part of the lab, you want to have your Macs running in Mac OS X mode!

Graphics and Chessboards

NQueensOnBoard.png

We didn't quite finish the display of the chessboard in class yesterday.

Let's finish it now.

Here's the program as we left it:

# classqueen.py
# A program that displays a chessboard on the screen
#
from graphics import *

def drawRow( win, H, W, N, border, side ):
    for i in range( 0, N, 2 ):
        x = border + i * side
        y = border
        x1 = x + side
        y1 = y + side
        r = Rectangle( Point( x, y ),
                       Point( x1, y1 ) )
        r.setFill( "black" )
        r.draw( win )

def     drawBoard( win, H, W, N, border, side ):
    # draw border
    r = Rectangle( Point( border, border ),
                   Point( W-border, H-border ) )
    r.draw( win )

    # draw small squares
    drawRow( win, H, W, N, border, side )

def main():
    N = 8
    border = 20
    W = H = 200
    side  = ( W - 2*border ) / N

    win = GraphWin( "board" )
    
    drawBoard( win, H, W, N, border, side )
    win.getMouse()
    win.close()


main()
Question 1
Create the program in your account, and run it. Verify that you get a window with the chessboard (Remember to start X11!)
Question 2
Classqueen1.png
Observe that the drawRow() function is set to draw only the first row. We would like to make it more general purpose, so that we can pass it a number indicating which row we want to display. For example, we could pass 0 in a new parameter indicating that the function is to display the first row. We could pass 1 to indicate that we want it to display the second row.
Modify the function drawRow() so that now it receives an new parameter, called row which will tell the function which row to display:
def drawRow( win, H, W, N, border, side, row ):
      ...
And in the function drawBoard( ), call drawRow() this way:
       drawRow( win, H, W, N, border, side, 0 )
       drawRow( win, H, W, N, border, side, 1 )
You should obtain a chessboard as shown on the right hand-side.
Question 3\
Alternating black-white squares
The trick now is to make the black squares start flush with the border, or offset by 1 side, so that even rows are going to be with black squares flush on the left, odd rows with black squares offset.
Open python in interactive mode, and play with these commands:
 >>> x = 1
 >>> x
 >>> x % 2
 >>> x = x + 1
 >>> x
 >>> x % 2
 >>> x = x + 1
 >>> x % 2
 >>> for x in range( 10 ):
 ...           print x % 2
 >>>
Also play with these commands
 >>> 
 >>> x = 20
 >>> x = 60 - x
 >>> x
 >>> x = 60 - x
 >>> x 
 >>> x = 60 - x
 >>> x
Figure out how to use what you have just learned so that you can modify the drawRow() function, and in particular the line
       x = border + i * side
so that if the parameter row is even, x is assigned border + i*side, but if it is odd, it is assigned border + side + i*side.
Question 4
Question 5
Question 6
Question 7
Question 8
Question 9