Difference between revisions of "CSC111 Lab 4 2015"

From dftwiki3
Jump to: navigation, search
 
(39 intermediate revisions by the same user not shown)
Line 2: Line 2:
 
----
 
----
  
=<center>Preparation for Homework #5</center>=
 
 
<br />
 
<br />
==String Methods==
+
__TOC__
 +
<br />
 +
=<center>Preparation for Homework #4</center>=
 +
<br />
 +
<showafterdate after="20150215 11:00" before="20200101 00:00">
 +
<br />
 +
<bluebox>
 +
This page contains exercises that will help you work out the solutions for the questions of Homework #4, which will be released after Wednesday's lecture (2/18/15).<br />
 +
Do not skip this step, and truly make an attempt at solving each problem.  The time you will spend now applying Python to solve the problems will save you time later, when we work on more challenging problems.<br />
 +
You will notice that the problems are getting more challenging.  This is because we are learning enough Python to solve more and more complex puzzles.  So it is important to practice solving problems.  DO NOT SKIP THIS PREPARATION PAGE!
 +
</bluebox>
 +
 +
==String Slices==
 +
 
 +
* Use Python in interactive mode and try the following Python statements.  Try to figure out the answers to the questions.
 +
 
 +
<code><pre>
 +
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]
  
[[Image:PythonYellowLogo.png | right |link=http://docs.python.org/lib/string-methods.html]]We have already seen several of these methods.  This lab is to reinforce our knowledge of strings.
+
>>> a[2]
  
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.
+
>>> a[-1]
  
Use emacs or the python interactive prompt to test out different methods, as we did in class yesterday.
+
>>> a[-2]
  
===center()===
+
>>> a[0 : 2]
  
One of the string methods is the '''center''' function.
+
>>> a[3 : 13]
  
Use it to center the title "computer SCIENCE 111" between two lines of 45 dashes. Use a variable called myTitle to store the string.
+
>>> a[-3 : -1]
  
        myTitle = "computer SCIENCE 111"
+
>>> a[-5 : -1]
        print 45*"-"
 
        print myTitle.center( 45 )
 
        print 45*"-"
 
  
===capitalize()===
+
>>> a[-5 : ]                  (no, I didn't forget the second number!)
  
Instead of printing the variable myTitle, print myTitle.'''capitalize'''( ) and see what happens.
+
>>> a[ : 3]                  (and no again, I didn't forget the first number!)
  
===upper()===
+
>>> a[3 : -3]
  
Use '''upper'''() instead of capitalize(). Observe the new output.
+
>>> b = "C:/My Documents/paper2.htm"
  
===title()===
+
>>> c = "Smith College"
 +
>>> for i in range( 5 ):
 +
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;              print( c[0:i] )
  
Same exercise, but with the '''title'''() method.
+
>>> for i in range( 5 ):
 +
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;              print( c[i:20] )
  
 +
</pre></code>
 +
You will have discovered that both '''a''' and '''b''' contain strings representing the name of files in a computer.
 +
< br />
 +
{| style="width:100%; background:silver"
 +
|-
 +
|
  
;Programming Question 1
+
===Challenge #1===
 +
|}
 +
[[Image:QuestionMark1.jpg|right|120px]]
  
: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.
+
* What is the string ''slice'' that will return the drive information for a (i.e. 'H:')?  If you slice '''b''' the same way, do you get the drive information as well? replace a by b, does your statement still return the drive for b?
  
:Example
+
:; Example of output:
your first name? alexAndra
+
<br />
your last name?  SMITH
+
:<source lang="text">
 +
H:/English103/paper1.doc --> H
 +
C:/My Documents/paper2.htm --> C
 +
</source>
 
   
 
   
------------------------------------------------------------
 
                      Alexandra Smith                     
 
------------------------------------------------------------
 
  
===Replacing substrings in a string===
+
<br />
 +
{| style="width:100%; background:silver"
 +
|-
 +
|
 +
 
 +
===Challenge #2===
 +
|}
 +
[[Image:QuestionMark2.jpg|right|120px]]
  
To replace a substring of a string (or a word in a sentence), all you need to do is to use the '''replace()''' method.
+
* What is the slice that will return the extension only of '''a''' or of '''b''' (i.e. ''doc'' or ''htm'')?
  
    sentence = """Strength is the capacity to break a chocolate
+
:; Example of output:
              bar into four pieces with your bare hands - and
+
<br />
              then eat just one of the pieces"""
+
:<source lang="text">
+
H:/English103/paper1.doc --> doc
    print sentence
+
C:/My Documents/paper2.htm --> htm
    sentence = sentence.replace( "chocolate", "carrot" )
+
</source>
    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.
+
<br />
 +
{| style="width:100%; background:silver"
 +
|-
 +
|
  
===Multiple Replacements===
+
===Challenge #3===
 +
|}
 +
[[Image:QuestionMark3.jpg|right|120px]]
  
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:
+
* 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".
  
  toBeReplaced = ["chocolate", "piece", "hand", "break"]
+
;:Example
  
and the replacement words are in this list:  
+
:::<tt>Filename? <u>C:/My Documents/paper02182010.doc</u></tt>
 +
:::<tt>C:/My Documents/paper02182010.txt</tt>
  
  newWords = ["carrot", "chunk", "elbow", "melt"]
+
<br />
 +
<br />
 +
<br />
 +
{| style="width:100%; background:silver"
 +
|-
 +
|
  
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'''.  
+
===Challenge #4===
 +
|}
 +
[[Image:QuestionMark4.jpg|right|120px]]
  
'''Use a for-loop!'''
+
* Write a program that asks the user for her first name and her last name, and outputs a computer account name, that is made of  the first letter of first name, plus the last name. (We won't worry about whether we have upper- or lower-case in the output.)
  
===Count()===
+
;:Example
  
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.
+
:::<tt>First name? <u>Allie</u></tt>
 +
:::<tt>Last name? <u>Baba</u></tt>
 +
:::<tt>Your computer account name is: ABaba</tt>
 +
<br />
 +
<br />
 +
<br />
 +
{| style="width:100%; background:silver"
 +
|-
 +
|
  
===Strip()===
+
===Challenge #5===
 +
|}
 +
[[Image:QuestionMark5.jpg|right|120px]]
  
Read the documentation about the method '''strip()''' and use it to allow you to print the lines below left aligned.
+
* Write a program that asks the user for her first and last names, and display a "triangle" with the names, as shown below:
 +
<br />
 +
<tt>Please enter your first name: <u>Maria</u></tt>
 +
<tt>Pleaes enter your last name: <u>LUCE</u></tt>
 +
<code><pre>
 +
M
 +
Ma
 +
Mar
 +
Mari
 +
Maria
 +
MariaL
 +
MariaLU
 +
MariaLUC
 +
MariaLUCE
 +
</pre></code>
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
==Indexing through a List==
 +
<br />
 +
This is an example taken from Section 5.3 in [https://docs.google.com/file/d/0BwyZgLoc-MkfcFdxTUNLLWd2Y2M/preview Zelle].  Add the code below to your current program.
 +
<br />
 +
<br />
 +
::<source lang="python">
 +
monthNames = ["January", "February", "March", "April", "May", "June", "July", "August",
 +
                      "September", "October", "November", "December"]
  
    listOfStrings = [ "         But then, shall I never get any older than I am now?     ",
+
month = eval( input( "Which month were you born in, as a number (1 for January)? " ) )
                            "    That'll be a comfort, one way -- never to be an old woman --          ",
 
                            "          but then -- always to have lessons to learn!          ",
 
                            "    Alice    " ]
 
  
===Splitting strings===
+
print( "You were born in", monthNames[ month-1 ] )
 +
</source>
 +
<br />
 +
<br />
 +
<br />
 +
{| style="width:100%; background:silver"
 +
|-
 +
|
  
First, read the documentation on the '''split()''' method.
+
===Challenge #6===
 +
|}
 +
[[Image:QuestionMark6.jpg|right|120px]]
  
Let's use the same string as before.
+
* Write a program that prompts the user for the day she was born, the month she was born, as a number, and the year she was born.  Your program will then output the birth date with the month as a word.
  
    sentence = """Strength is the capacity to break a chocolate
+
;:Example
              bar into four pieces with your bare hands - and
 
              then eat just one of the pieces"""
 
  
And process it that way
+
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Day you were born? <u>14</u>
   
+
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Month you were born? <u>2</u>
    list1 = sentence.split( "\n" )
+
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Year you were born? <u>1990</u>
    print "list1 = ", list1
 
 
   
 
   
    list2 = sentence.split( )
+
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;You were born on February 14, 1990
    print "list2 = ", list2
 
 
   
 
   
    list3 = sentence.split( 's' )
+
<br />
    print "list3 = ", list3
+
<br />
 +
<br />
 +
<br />
 +
{| style="width:100%; background:silver"
 +
|-
 +
|
 +
 
 +
===Challenge #7===
 +
|}
 +
[[Image:QuestionMark9.jpg|right|120px]]
 +
 
 +
* Modify your solution for Challenge 6 so that it outputs the first 3 letters of the month, only.  You cannot modify the list of months. In other words, the only list you can have in your program is
 +
<br />
 +
:::<source lang="python">
 +
monthNames = ["January", "February", "March", "April", "May", "June", "July", "August",
 +
                      "September", "October", "November", "December"]
 +
</source>
 +
<br />
  
;Programming Question 2
+
<br />
 +
<br />
 +
<br />
 +
<br />
 +
==Splitting Strings==
 +
<br />
 +
* Use the Python Shell to explore the '''split()''' method for strings.
 +
<br />
 +
<code><pre>
 +
>>> phrase = "The quick red fox jumped over the fox"
 +
>>> phrase
  
:Make your program print the number of words in '''sentence''' (there are several ways to do that: one long, one very short).
+
>>> words = phrase.split()
 +
>>> words
  
;Programming Question 3
+
>>> words[0]
  
:Make your program display the first and last words of the sentence.
+
>>> words[-1]
  
; Programming Question 4
+
>>> words[0:2]
  
:Assume that you have a string of this type:
+
>>> words[3]
  
    NYTBestSellers = """1. THE HELP, by Kathryn Stockett
+
>>> for i in range( len( words ) ):
                                2. WORST CASE, by James Patterson and Michael Ledwidge
+
    print( words[ i ] )
                                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:
+
>>>
 +
>>> for i in range( len( words )-1, -1, -1 ):
 +
    print( words[i] )
  
  Kathryn Stockett                                    The Help
+
>>> for word in words:
  James Patterson and Michael Ledwidge                Worst Case
+
            print( word )
  Dan Brown                                            The Lost Symbol
 
  Jackie Collins                                      Poor Little Bitch Girl
 
  Kristin Hannah                                      Winter Garden
 
  
<tanbox>
+
>>> dwarves = "Doc, Grumpy, Happy, Sleepy, Bashful, Sneezy, Dopey"
For this part of the lab, you want to have your Macs running in Mac OS X mode!
+
>>> dwarves
</tanbox>
 
  
==String Slices==
+
>>> names = dwarves.split( ", " )
 +
>>> names
  
* Use Python in interactive mode and try the following Python statements.  Try to figure out the answers to the questions.
+
>>> for name in names:
 +
          print( name )
 +
>>>
  
<code><pre>
+
</pre></code>
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 )
+
<br />
 +
{| style="width:100%; background:silver"
 +
|-
 +
|
  
>>> a[0 : 2]
+
===Challenge #8===
 +
|}
 +
[[Image:QuestionMark8.jpg|right|120px]]
  
>>> a[3 : 13]
+
* Write a program that asks the user to enter a sentence made of words separated by spaces.  Your program will then output the words, one on each line, right justified in a field of 30 characters.
 +
<br />
 +
:;Example
 +
:<source lang="text">
 +
Enter a sentence: The quick red fox jumped over the dog
 +
                          The
 +
                        quick
 +
                          red
 +
                          fox
 +
                        jumped
 +
                          over
 +
                          the
 +
                          dog
 +
</source>
 +
<br />
  
>>> a[-3 : -1]
+
==String Methods==
  
>>> a[-5 : -1]
+
[[Image:PythonYellowLogo.png | right |link=http://docs.python.org/lib/string-methods.html]] We have already seen a string method: the '''format()''' method, used with the {...} formatting satatement. 
  
>>> a[-5 : ]                  (no, I didn't forget the second number!)
+
Chapter 5 introduces a few more.
  
>>> a[ : 3]                   (and no again, I didn't forget the first number!)
+
The methods are all documented at this page: [https://docs.python.org/3/library/stdtypes.html#string-methods https://docs.python.org/3/library/stdtypes.html#string-methods]. Open this page and refer to it  while you are working on this prep. lab.
  
>>> a[3 : -3]
+
Use  the python shell to test out different string methods:
  
>>> b = "C:/My Documents/paper2.htm"
+
===center()===
  
</pre></code>
+
One of the string methods is the '''center''' function.
You will have discovered that both '''a''' and '''b''' contain strings representing the name of files on a computer.
 
;Question 4
 
: 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 5
+
Use it to center the title "computer SCIENCE 111" between two lines of 45 dashes. Use a variable called myTitle to store the string.
: 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.
+
<br />
 +
::<source lang="python">
 +
myTitle = "computer SCIENCE 111"
 +
print( 45*"-" )
 +
print( myTitle.center( 45 ) )
 +
print( 45*"-" )
 +
</source>
 +
<br />
 +
===capitalize()===
 +
<br />
 +
Instead of printing the variable myTitle, print myTitle.'''capitalize'''( ) and see what happens.
 +
<br />
 +
===upper()===
 +
<br />
 +
Use '''upper'''() instead of capitalize(). Observe the new output.
 +
<br />
 +
===title()===
 +
<br />
 +
Same exercise, but with the '''title'''() method.
 +
<br />
 +
{| style="width:100%; background:silver"
 +
|-
 +
|
  
;Question 6
+
===Challenge #9===
: 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".
+
|}
 +
[[Image:QuestionMark9.jpg|right|120px]]
  
::Example
+
*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.
  
:::<tt>Filename? <u>C:/My Documents/paper02182010.doc</u></tt>
+
;Example
:::<tt>C:/My Documents/paper02182010.txt</tt>
+
<br />
 +
<source lang="text">
 +
your first name? alexAndra
 +
your last name?  SMITH
 +
 +
------------------------------------------------------------
 +
                      Alexandra Smith                     
 +
------------------------------------------------------------
 +
</source>
 +
<br />
  
 +
===Replacing substrings in a string===
 
<br />
 
<br />
 +
To replace a substring of a string (or a word in a sentence), all you need to do is to use the '''replace()''' method.
 
<br />
 
<br />
 +
::<source lang="python">
 +
    # we define a multi-line string with triple-double-quotes
 +
    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"""
 +
 +
    # display original string
 +
    print( "Original sentence =", sentence )
 +
 +
    # replace chocolate by carrot
 +
    sentence = sentence.replace( "chocolate", "carrot" )
 +
 +
    # display resulting string
 +
    print( "New sentence = ", sentence )
 +
</source>
 
<br />
 
<br />
 +
Try it and replace the word "piece" by the word "chunk" in the same sentence, so that now you're breaking carrots into chunks.
 
<br />
 
<br />
 +
===Count()===
 
<br />
 
<br />
 +
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.
 
<br />
 
<br />
 +
===Strip()===
 
<br />
 
<br />
 +
Read the documentation about the method '''strip()''' and use it to allow you to print the lines below left aligned.
 
<br />
 
<br />
 +
::<source lang="python">
 +
 +
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    " ]
 +
</source>
 
<br />
 
<br />
 +
</showafterdate>
 
<br />
 
<br />
  
<showafterdate after="20150215 00:00" before="20150601 00:00">
+
<showafterdate after="20150218 11:00" before="20150601 00:00">
 
=Solution Programs=
 
=Solution Programs=
 +
<br />
 +
<source lang="python">
 +
# lab4Prep.py
 +
# D. Thiebaut
 +
# Solution program for Lab4/prep
 +
# MAKE SURE YOU TRY THE CHALLENGES BY YOURSELF, ON YOUR OWN,
 +
# BEFORE YOU LOOKUP THE SOLUTION.
 +
#
 +
 +
def challenge1():
 +
    b = "C:/My Documents/paper2.htm"
 +
    a = "H:/English103/paper1.doc"
 +
    drive = a[0:1]
 +
    print( a, "-->", drive )
 +
    drive = b[0:1]
 +
    print( b, "-->", drive )
 +
 +
def challenge2():
 +
    b = "C:/My Documents/paper2.htm"
 +
    a = "H:/English103/paper1.doc"
 +
    extension = a[-3:]
 +
    print( a, "-->", extension )
 +
    extension = b[-3:]
 +
    print( b, "-->", extension )
 +
 +
def challenge3():
 +
    fileName = "C:/document/CSC111_finalExam.sol" # input( "File name? " )
 +
    fileNameNoExt = fileName[0:-3]
 +
    newFileName  = fileNameNoExt + "txt"
 +
    print( fileName, "-->", newFileName )
 +
 +
def challenge4():
 +
    fName = "Allie" #input( "Your first name? " )
 +
    lName = "Baba"  #input( "Your last name? " )
 +
    account = fName[0] + lName
 +
    print( fName, lName, "your computer account is", account )
 +
 +
def challenge5():
 +
    fName = "Maria" #input( "Your first name? " )
 +
    lName = "LUCE"  #input( "Your last name? " )
 +
    fullName = fName + lName
 +
    noChars  = len( fullName )
 +
    for i in range( 1, noChars + 1 ):
 +
        print( fullName[0:i] )
 +
 +
def challenge6():
 +
    monthNames = ["January", "February", "March", "April", "May", "June", "July", "August",
 +
                  "September", "October", "November", "December"]
 +
 +
    day  = 14      #eval( input( "Day? " ) )
 +
    month = 2      #eval( input( "Month (as a number)? " ) )
 +
    year  = 1990    #eval( input( "Year? " ) )
 +
   
 +
    monthString = monthNames[ month ]
 +
    print()
 +
    print( "You were born on {0:1} {1:1}, {2:1}."
 +
          .format( day,  monthString, year ) )
 +
    print()
 +
 +
def challenge7():
 +
    monthNames = ["January", "February", "March", "April", "May", "June", "July", "August",
 +
                  "September", "October", "November", "December"]
 +
 +
    day  = 14      #eval( input( "Day? " ) )
 +
    month = 2      #eval( input( "Month (as a number)? " ) )
 +
    year  = 1990    #eval( input( "Year? " ) )
 +
   
 +
    monthString = monthNames[ month ]
 +
    print()
 +
    print( "You were born on {0:1} {1:1}, {2:1}."
 +
          .format( day,  monthString[0:3], year ) )
 +
    print()
 +
 +
def challenge8():
 +
    sentence = "the quick fox jumped over the lazy dog" #input( "Enter a sentence: " )
 +
    words = sentence.split( )
 +
    for word in words:
 +
        print( "{0:>30}".format( word ) )
 +
 +
 +
def challenge9():
 +
    fName = "Alexandra" #input( "Your first name? " )
 +
    lName = "Smith"    #input( "Your last name? " )
 +
    name = fName + " " + lName
 +
    bar  = 60 * '-'
 +
    print( bar )
 +
    print( name.center( 60 ) )
 +
    print( bar )
 +
   
 +
def main():
 +
    challenge1()
 +
    challenge2()
 +
    challenge3()
 +
    challenge4()
 +
    challenge5()
 +
    challenge6()
 +
    challenge7()
 +
    challenge8()
 +
    challenge9()
 +
   
 +
 +
main()
  
 +
</source>
  
 
</showafterdate>
 
</showafterdate>

Latest revision as of 18:11, 22 February 2015

--D. Thiebaut (talk) 17:39, 14 February 2015 (EST)




Preparation for Homework #4


<showafterdate after="20150215 11:00" before="20200101 00:00">

This page contains exercises that will help you work out the solutions for the questions of Homework #4, which will be released after Wednesday's lecture (2/18/15).
Do not skip this step, and truly make an attempt at solving each problem. The time you will spend now applying Python to solve the problems will save you time later, when we work on more challenging problems.
You will notice that the problems are getting more challenging. This is because we are learning enough Python to solve more and more complex puzzles. So it is important to practice solving problems. DO NOT SKIP THIS PREPARATION PAGE!

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]

>>> a[2]

>>> a[-1]

>>> a[-2]

>>> 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"

>>> c = "Smith College"
>>> for i in range( 5 ):
                       print( c[0:i] )

>>> for i in range( 5 ):
                       print( c[i:20] )

You will have discovered that both a and b contain strings representing the name of files in a computer. < br />

Challenge #1

QuestionMark1.jpg
  • What is the string slice that will return the drive information for a (i.e. 'H:')? If you slice b the same way, do you get the drive information as well? replace a by b, does your statement still return the drive for b?
Example of output


 
H:/English103/paper1.doc --> H
C:/My Documents/paper2.htm --> C



Challenge #2

QuestionMark2.jpg
  • What is the slice that will return the extension only of a or of b (i.e. doc or htm)?
Example of output


 
H:/English103/paper1.doc --> doc
C:/My Documents/paper2.htm --> htm


Challenge #3

QuestionMark3.jpg
  • 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




Challenge #4

QuestionMark4.jpg
  • Write a program that asks the user for her first name and her last name, and outputs a computer account name, that is made of the first letter of first name, plus the last name. (We won't worry about whether we have upper- or lower-case in the output.)
Example
First name? Allie
Last name? Baba
Your computer account name is: ABaba




Challenge #5

QuestionMark5.jpg
  • Write a program that asks the user for her first and last names, and display a "triangle" with the names, as shown below:


Please enter your first name: Maria Pleaes enter your last name: LUCE

M
Ma
Mar
Mari
Maria
MariaL
MariaLU
MariaLUC
MariaLUCE





Indexing through a List


This is an example taken from Section 5.3 in Zelle. Add the code below to your current program.

monthNames = ["January", "February", "March", "April", "May", "June", "July", "August",
                       "September", "October", "November", "December"]

month = eval( input( "Which month were you born in, as a number (1 for January)? " ) )

print( "You were born in", monthNames[ month-1 ] )




Challenge #6

QuestionMark6.jpg
  • Write a program that prompts the user for the day she was born, the month she was born, as a number, and the year she was born. Your program will then output the birth date with the month as a word.
Example
     Day you were born? 14
     Month you were born? 2 
     Year you were born? 1990 

     You were born on February 14, 1990 





Challenge #7

QuestionMark9.jpg
  • Modify your solution for Challenge 6 so that it outputs the first 3 letters of the month, only. You cannot modify the list of months. In other words, the only list you can have in your program is


 monthNames = ["January", "February", "March", "April", "May", "June", "July", "August",
                       "September", "October", "November", "December"]






Splitting Strings


  • Use the Python Shell to explore the split() method for strings.


>>> phrase = "The quick red fox jumped over the fox"
>>> phrase

>>> words = phrase.split()
>>> words

>>> words[0]

>>> words[-1]

>>> words[0:2]

>>> words[3]

>>> for i in range( len( words ) ):
	    print( words[ i ] )

>>> 
>>> for i in range( len( words )-1, -1, -1 ):
	    print( words[i] )

>>> for word in words:
            print( word )

>>> dwarves = "Doc, Grumpy, Happy, Sleepy, Bashful, Sneezy, Dopey"
>>> dwarves

>>> names = dwarves.split( ", " )
>>> names

>>> for name in names:
           print( name )
>>> 


Challenge #8

QuestionMark8.jpg
  • Write a program that asks the user to enter a sentence made of words separated by spaces. Your program will then output the words, one on each line, right justified in a field of 30 characters.


Example
Enter a sentence: The quick red fox jumped over the dog
                           The
                         quick
                           red
                           fox
                        jumped
                          over
                           the
                           dog


String Methods

PythonYellowLogo.png
We have already seen a string method: the format() method, used with the {...} formatting satatement.

Chapter 5 introduces a few more.

The methods are all documented at this page: https://docs.python.org/3/library/stdtypes.html#string-methods. Open this page and refer to it while you are working on this prep. lab.

Use the python shell to test out different string methods:

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.

Challenge #9

QuestionMark9.jpg
  • 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.

    # we define a multi-line string with triple-double-quotes
    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"""
 
    # display original string
    print( "Original sentence =", sentence )

    # replace chocolate by carrot
    sentence = sentence.replace( "chocolate", "carrot" )

    # display resulting string
    print( "New sentence = ", 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.

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    " ]


</showafterdate>

<showafterdate after="20150218 11:00" before="20150601 00:00">

Solution Programs


# lab4Prep.py
# D. Thiebaut
# Solution program for Lab4/prep
# MAKE SURE YOU TRY THE CHALLENGES BY YOURSELF, ON YOUR OWN, 
# BEFORE YOU LOOKUP THE SOLUTION.
#

def challenge1():
    b = "C:/My Documents/paper2.htm"
    a = "H:/English103/paper1.doc"
    drive = a[0:1]
    print( a, "-->", drive )
    drive = b[0:1]
    print( b, "-->", drive )

def challenge2():
    b = "C:/My Documents/paper2.htm"
    a = "H:/English103/paper1.doc"
    extension = a[-3:]
    print( a, "-->", extension )
    extension = b[-3:]
    print( b, "-->", extension )

def challenge3():
    fileName = "C:/document/CSC111_finalExam.sol" # input( "File name? " )
    fileNameNoExt = fileName[0:-3]
    newFileName   = fileNameNoExt + "txt"
    print( fileName, "-->", newFileName )

def challenge4():
    fName = "Allie" #input( "Your first name? " )
    lName = "Baba"  #input( "Your last name? " )
    account = fName[0] + lName
    print( fName, lName, "your computer account is", account )

def challenge5():
    fName = "Maria" #input( "Your first name? " )
    lName = "LUCE"  #input( "Your last name? " )
    fullName = fName + lName
    noChars  = len( fullName )
    for i in range( 1, noChars + 1 ):
        print( fullName[0:i] )

def challenge6():
    monthNames = ["January", "February", "March", "April", "May", "June", "July", "August",
                  "September", "October", "November", "December"]

    day   = 14      #eval( input( "Day? " ) )
    month = 2       #eval( input( "Month (as a number)? " ) )
    year  = 1990    #eval( input( "Year? " ) )
    
    monthString = monthNames[ month ]
    print()
    print( "You were born on {0:1} {1:1}, {2:1}."
           .format( day,  monthString, year ) )
    print()

def challenge7():
    monthNames = ["January", "February", "March", "April", "May", "June", "July", "August",
                  "September", "October", "November", "December"]

    day   = 14      #eval( input( "Day? " ) )
    month = 2       #eval( input( "Month (as a number)? " ) )
    year  = 1990    #eval( input( "Year? " ) )
    
    monthString = monthNames[ month ]
    print()
    print( "You were born on {0:1} {1:1}, {2:1}."
           .format( day,  monthString[0:3], year ) )
    print()

def challenge8():
    sentence = "the quick fox jumped over the lazy dog" #input( "Enter a sentence: " )
    words = sentence.split( )
    for word in words:
        print( "{0:>30}".format( word ) )


def challenge9():
    fName = "Alexandra" #input( "Your first name? " )
    lName = "Smith"     #input( "Your last name? " )
    name = fName + " " + lName
    bar  = 60 * '-'
    print( bar )
    print( name.center( 60 ) )
    print( bar )
    
def main():
    challenge1()
    challenge2()
    challenge3()
    challenge4()
    challenge5()
    challenge6()
    challenge7()
    challenge8()
    challenge9()
    

main()

</showafterdate>