Difference between revisions of "CSC111 Lab 5 2018"

From dftwiki3
Jump to: navigation, search
Line 477: Line 477:
 
::<source lang="python">
 
::<source lang="python">
 
   
 
   
 +
  
 
# --------------------- stickFigure -----------------------
 
# --------------------- stickFigure -----------------------
Line 566: Line 567:
  
 
# ---------------------- Snow Man ----------------------
 
# ---------------------- Snow Man ----------------------
"""
+
_ = """
 
     __
 
     __
 
   _|==|_
 
   _|==|_
Line 574: Line 575:
 
   `======'
 
   `======'
 
"""
 
"""
def hat():
+
def hat2():
 
     print("    __" )
 
     print("    __" )
 
     print("  _|==|_" )
 
     print("  _|==|_" )
  
def headRightArm():
+
def headRightArm2():
 
     print( "    ('')__/" )
 
     print( "    ('')__/" )
  
def leftArm():
+
def leftArm2():
 
     print( ">--", end="" )
 
     print( ">--", end="" )
  
def body():
+
def body2():
 
     print( "(`^^`)" )
 
     print( "(`^^`)" )
 
     print("  (`^'^'`)" )
 
     print("  (`^'^'`)" )
  
def base():
+
def base2():
 
     print( "  `======'" )
 
     print( "  `======'" )
 
     print()
 
     print()
 
      
 
      
 
def snowMan():
 
def snowMan():
     hat()
+
     hat2()
     headRightArm()
+
     headRightArm2()
     leftArm()
+
     leftArm2()
     body()
+
     body2()
     base()
+
     base2()
   
 
 
 
snowMan()
 
 
 
 
      
 
      
  
Line 643: Line 640:
 
def singHappy2( ):
 
def singHappy2( ):
 
     # get a line of names, separated by spaces
 
     # get a line of names, separated by spaces
     line = input( "? " )
+
     line = input( "Give me several names, please: " )
  
 
     # remove extra spaces at the front or back
 
     # remove extra spaces at the front or back
Line 658: Line 655:
 
     print( "\n" + ( "-"*30 ) + "oOo" + ("-"*30 ) +"\n" )
 
     print( "\n" + ( "-"*30 ) + "oOo" + ("-"*30 ) +"\n" )
  
 +
def identifyDNA( DNA ):
 +
    return DNA.replace( "AGA", "###" )
 +
 +
def trimDNA( DNA ):
 +
    marker = "AGA"
 +
    index1 = DNA.find( marker )
 +
    index2 = DNA.find( marker, index1+1 )
 +
    return DNA[index1:index2 + len( marker )]
 +
 +
def DNAProblem():
 +
    DNA = "AAGACTAAAAAAGACTT" #input( "Enter DNA: " )
 +
    print( "DNA =", DNA )
 
      
 
      
 +
    # show where the markers are
 +
    newDNA = identifyDNA( DNA )
 +
    print( newDNA )
 +
 +
    # remove symbols on each side of the markers
 +
    newDNA = trimDNA( DNA )
 +
    print( newDNA )
 +
 +
def challenge4():
 +
    sentence = "the quick red fox jumped" # input( "Sentence? " )
 +
    print( "Sentence =", sentence )
 +
    sum = 0
 +
    words = sentence.split()
 +
    for word in words:
 +
        sum = sum + len( word )
 +
    print( "average word length = {0:1.2f}".format( sum/len(words) ) )
 +
 +
def challenge5():
 +
    students = ["Brown,Sarah", "McCharles,Charlie", "Hudson,Stanley",
 +
                "Smith,Margaret", "Brown,Ben", "Yang,Debbie"]
 +
   
 +
    # display the students
 +
    for i in range( len( students ) ):
 +
        print( i, students[i] )
 +
 +
    # get index from user
 +
    index = 3 # input( "Which student? " )
 +
    name = students[index]
 +
    last, first = name.split( ',' )
 +
    account = first[0] + last
 +
    account = account.lower()
 +
    print( name, account )
 +
 
def main():
 
def main():
 
     newStickFigure()
 
     newStickFigure()
Line 665: Line 707:
 
     singHappy()
 
     singHappy()
 
     singHappy2()
 
     singHappy2()
 
+
    DNAProblem()
 +
    challenge4()
 +
    challenge5()
 +
   
 
main()
 
main()
  

Revision as of 08:18, 25 February 2018

D. Thiebaut (talk) 05:52, 25 February 2018 (EST)





<showafterdate after="20180228 11:00" before="20180601 00:00">

This lab deals with functions, passing parameters, and returning values. It is also about for you to start the Python.org documentation on the Web. The online documentation is a great help when writing programs. The Moodle submissions are due on Friday 10/09 at 11:55 p.m.



Searching the Python.org Docs

Python org.png


  • Open your Web browser and go to http://python.org
  • Click on Documentation, then on Python 3.x Docs.
  • In the Search Bar on the left, enter string methods.
  • Locate the result that contains Built-In Types, and go to that page. Locate the string methods there... (Hints: 4.7.1)
  • Look at all the different methods that strings offer you.
  • You're ready for the lab!


Functions


Working with Functions in the Console


  • This sections serves as a review for the end="..." optional parameter in print statements.
  • Try the following statements in the Python console:


>>> def test():
	print( "hello" )
	print( "there" )

	
>>> test()


>>> def test():
	print( "hello", end="" )
	print( "there" )

	
>>> test()

>>> def test():
	print( "hello", end="-" )
	print( "there" )

	
>>> test()
>>>


Notice what happens when you add the end="" construct in the print statement. It changes the way the print() function ends printing what it has to print. By default, if you do not have an end="" construct, print() brings the cursor to the next line. But this behavior can be changed. We are going to use this, in the new program below.

Teller Machine with Functions

TellerFigure.jpg


  • Without looking at your notes, (but if you get stuck, it's ok to look up your notes or the class notes on the Web), try to recreate the teller machine program, where a user enters an integer amount of dollars, and gets some number of bills back.
  1. Start with the main program, have it call a function to get the amount (you can call it getAmount()), then it calls a function (say divideInBills()), that receives the amount, breaks it into 4 numbers, and returns a list of 4 numbers to main. And finally, at the end of main(), a function (say, displayResults()) is passed the list of 4 numbers and prints them in a nicely formatted output. Below is a skeleton for you to start with:


# teller.py


# getAmount: prompts the user for an amount
# returns the amount back
def getAmount():
   ...

# divideInBills: gets the integer amount of dollars
# and prints on the screen the number of $20-, $10-,
# $5- and $1-bills.
def divideInBills( amount ):
   ...

def main():
   # get amount from user
   amount = getAmount()

   # break the amount in bills
   divideInBills( amount )

main()


Challenge #1

QuestionMark5.jpg
  • Once your program works, you will notice that you have 4 lines of code in divideInBills() that look like this:


   num20s = amount // x
   amount = amount % x


where x is 20, then 10, then 5, and finally 1.


Just for fun, you are going to create a new function called breakDown( ... )' that gets the amount and x, and that returns the number of bills corresponding to x, along with the new amount:


def breakDown( amount, x ):
    ...

def divideInBills( amount ):
    amount, no20s = breakDown( amount, 20 )
    amount, no10s = breakDown( amount, 10 )
    amount, no5s = breakDown( amount, 5 )
    amount, no1s = breakDown( amount, 1 )  # (this code is not necessarily efficient)
    
    # add your print statements below
    ...







Functions and Stick Figure, Version 1


  • This section will be cleaner if you start a new program, rather than add to an existing program.
  • Add this code section to your new program:


def head():
    print( "  o" )

def leftArm():
    print( " /", end="" )

def torso():
    print( "O", end="" )

def rightArm():
    print( "\\" )

def leftLeg():
    print( " /", end="" )

def rightLeg():
    print( " \\" )

def stickFigure():
    head()
    leftArm()
    torso()
    rightArm()
    leftLeg()
    rightLeg()

def main():
    stickFigure()

main()


  • Take a close look at the program. Locate the end="" construct, which prevents the print from going to the next line when it's done.
  • Notice also the "\\" string. Because the '\' character is used to print special characters, like '\n' (new line), or '\t' (tab), if we want to print a regular backslash character, we have to use 2 backslashes next to each other.


  • Run the program. Notice how it displays a stick figure.


Functions and Stick Figure, Version 2


  • Modify the stick figure program so that it looks like the code below:


def head():
    print( "  o" )

def leftArm():
    print( " /", end="" )

def torso():
    print( "O", end="" )

def rightArm():
    print( "\\" )

def leftLeg():
    print( " /", end="" )

def rightLeg():
    print( " \\" )

def body():
    leftArm()
    torso()
    rightArm()

def newStickFigure():
    head()
    body()
    leftLeg()
    rightLeg()

def main():
    newStickFigure()

main()
  • Observe how the code is different, and the new function body() is used to display the body of the stick figure (torso plus arms).
  • Using the example of body(), add a new function called legs() that will call leftLeg() and rightLeg() to draw both legs. Modify newStickFigure() by removing the calls to leftLeg() and rightLeg(), and adding instead a call to legs(). Your new function should look something like this:


def newStickFigure():
    head()
    body()
    legs()


Functions and Stick Figure, Version 3


     __
   _|==|_
    ('')__/
>--(`^^`)
  (`^'^'`)
  `======'


  • Use the same approach to create the stick figure of a snow man, above, using the function snowMan() shown below:


def snowMan():
    hat()
    headRightArm()
    leftArm()
    body()
    base()



Trimming DNA


  • Assume that we get a string from the user containing the description of a DNA sequence, for example "AAGACTAAAAAAGACTT." (DNA sequences are made of 4 symbols: A, C, G, and T.) Assume that all the DNA strings the user works with always contain two special substrings (markers) equal to "AGA". So our DNA string is marked in this way: "AAGACTAAAAAAGACTT."
  • Write a function called trimDNA( ) that receives a DNA string provided by the user, and returns the string where everything on the left and right of the markers has been removed. We assume that the string will always contain the two markers, so you do not have to worry about not finding the markers. You may want to search for the find() string method in the Python.org documentation to see how to find the second marker once you found the first one.
  • Example:


def trimDNA( DNA ):
     ...

def main():
     DNA = input( "Enter DNA: " )  # example: "AAGACTAAAAAAGACTT"
     newDNA = trimDNA( DNA )
     print( newDNA )


  • The output would be
 AGACTAAAAAAGA


Testing


Make sure your function works strings of the type AAGAAGACTT, or AGATTTTAGA.

  • Add a new function to your program called identifyMarkers() that receives the DNA string and returns a different version of it, where the markers are replaced by three '#' characters.


def identifyMarkers( DNA ):
     ...

def main():
     DNA = input( "Enter DNA: " )  # example: "AAGACTAAAAAAGACTT"
     # show where the markers are
     newDNA = identifyDNA( DNA )
     print( newDNA )

     # remove symbols on each side of the markers
     newDNA = trimDNA( DNA )
     print( newDNA )


the output would be:


Enter DNA: AAGACTAAAAAAGACTT
A###CTAAAAA###CTT
AGACTAAAAAAGA



Happy Birthday!


  • Start with these three new functions:


def happyBirthday():
    print( "Happy birthday to you!" )

def happyBirthdayDear( name ):
    print( ("Happy birthday, dear " + name +"!" ) )


  • Write a third function called singSong() that calls the two functions above. When calling happyBirthdayDear( ... ), pass it some name, say yours, or "Dave", or one of your friends. You should get this kind of output:


Happy birthday to you!
Happy birthday, dear Dave!


  • Modify singSong() so that it displays a more appropriate version on the song:


Happy birthday to you!
Happy birthday to you!
Happy birthday, dear Dave!
Happy birthday to you!


Passing the Name as a Parameter


  • Modify your singSong( ) function one more time. I'm highlighting the lines that should change in your function:


def singSong( name ):
     ...
     ...
     happyBirthdayDear( name )
     ...


  • Now, make your program sing "Happy Birthday" to Dave, Karl, Jorge, and Tim!


Challenge #2

QuestionMark8.jpg
  • Make your program prompt the user for a name in the main() function.
  • Then main() will pass the name to singSong(), and your program will sing Happy Birthday to the person of your choice.






Challenge #3

QuestionMark9.jpg


  • Modify your solution program for the previous challenge so that the user can enter several names on one line when prompted by your program. Your program then "sings" happy birthday to all the friends, one after the other...


  • Example:


Please enter the names of your friends: Jorge KARL         Dave

Happy birthday to you!
Happy birthday to you!
Happy birthday, dear Jorge!
Happy birthday to you!

Happy birthday to you!
Happy birthday to you!
Happy birthday, dear Karl!
Happy birthday to you!

Happy birthday to you!
Happy birthday to you!
Happy birthday, dear Dave!
Happy birthday to you!


Moodle Submission


  • Submit your solution program for Challenge 3 to Moodle, in Section LAB 5 PB 3. You will need to rename your program lab5_3.py.




Challenging Problems of the Day

Challenge #4

QuestionMark3.jpg



  • Write a program prompt the user for a sentence of several words.
  • Make your program calculate the average word length of all the words in the sentence.
  • Make your program outpu the average word length with TWO decimal places.
  • Example output:
Sentence? the quick red fox jumped
average word length = 4.00


Challenge #5

QuestionMark5.jpg


Write a program that does the following: 1. It contains a string with a list of student names:

    students = ["Brown,Sarah", "McCharles,Charlie", "Hudson,Stanley", 
                "Smith,Margaret", "Brown,Ben", "Yang,Debbie"]

2. It displays the list of names on the screen, with an index in front of each one. 2. It prompts the user to type in an integer number between 0 and 5, included. 3. Using this number, it gets the appropriate student name and prints out a new computer account with format First Initial Last Name

        ie. Sarah Brown turns into sbrown.

4. Use functions!

Example Input/Output

>>> main()
0 Brown,Sarah
1 McCharles,Charlie
2 Hudson,Stanley
3 Smith,Margaret
4 Brown,Ben
5 Yang,Debbie
Which student do you want to process? 5

Debbie Yang: dyang
>>> 

Moodle Submission


  • Submit your solution program for Challenge 5 to Moodle, in Section LAB 5 PB 5. You should call your program lab5_5.py, or copy/paste your program in the Edit window in Moodle.



</showafterdate>


<showafterdate after="20180309 08:00" before="20180601 00:00">

Solution Programs


 


# --------------------- stickFigure -----------------------

def head():
    print( "  o" )

def leftArm():
    print( " /", end="" )

def torso():
    print( "O", end="" )

def rightArm():
    print( "\\" )

def leftLeg():
    print( " /", end="" )

def rightLeg():
    print( " \\" )

def stickFigure():
    head()
    leftArm()
    torso()
    rightArm()
    leftLeg()
    rightLeg()

def body():
    leftArm()
    torso()
    rightArm()

def legs():
    leftLeg()
    rightLeg()

def newStickFigure():
    head()
    body()
    legs()

# --------------------- stickFigure1 ----------------------

def leftForearm1():
    print( " /", end="" )

def sword1():
    print( "+=====>" )

def leftArm1():
    print( " \\", end="" )

def head1():
    print( "O", end="" )

def rightArm1():
    print( "___" )

def body1():
    print( "  |" )
    print( "  |" )

def leftThigh1():
    print( " / ", end="" )

def rightThigh1():
    print( "\\" )

def leftCalf1():
    print( "/   ", end ="" )

def rightCalf1():
    print( "\\" )

def stickFigure1():
    leftForearm1()
    sword1()
    leftArm1()
    head1()
    rightArm1()
    body1()
    leftThigh1()
    rightThigh1()
    leftCalf1()
    rightCalf1()

# ---------------------- Snow Man ----------------------
_ = """
     __
   _|==|_
    ('')__/
>--(`^^`)
  (`^'^'`)
  `======'
"""
def hat2():
    print("     __" )
    print("   _|==|_" )

def headRightArm2():
    print( "    ('')__/" )

def leftArm2():
    print( ">--", end="" )

def body2():
    print( "(`^^`)" )
    print("  (`^'^'`)" )

def base2():
    print( "  `======'" )
    print()
    
def snowMan():
    hat2()
    headRightArm2()
    leftArm2()
    body2()
    base2()
    

    
# ---------------------------------------------------------


def happyBirthday():
    print( "Happy birthday to you!" )

def happyBirthdayDear( name ):
    print( "Happy birthday, dear " + name +"!"  )

def singSong( name ):
    happyBirthday()
    happyBirthday()
    happyBirthdayDear( name )
    happyBirthday()


def singHappy( ):
    # get the name from the user
    name = input( "Who's birthday should we celebrate? " )

    # sing the song for that person
    singSong( name )

# ----------------- Another Version ---------------------
def happyBirthday():
    print( "Happy birthday to you!" )

def happyBirthdayDear( name ):
    print( "Happy birthday, dear " + name +"!"  )

def singSong( name ):
    happyBirthday()
    happyBirthday()
    happyBirthdayDear( name )
    happyBirthday()

def singHappy2( ):
    # get a line of names, separated by spaces
    line = input( "Give me several names, please: " )

    # remove extra spaces at the front or back
    line = line.strip()

    # split the line into individual names, and sing song for each
    for name in line.split(  ):
        singSong( name )
        # blank line separates the different songs
        print()


def bar():
    print( "\n" + ( "-"*30 ) + "oOo" + ("-"*30 ) +"\n" )

def identifyDNA( DNA ):
    return DNA.replace( "AGA", "###" )

def trimDNA( DNA ):
    marker = "AGA"
    index1 = DNA.find( marker )
    index2 = DNA.find( marker, index1+1 )
    return DNA[index1:index2 + len( marker )]

def DNAProblem():
    DNA = "AAGACTAAAAAAGACTT" #input( "Enter DNA: " )
    print( "DNA =", DNA )
    
    # show where the markers are
    newDNA = identifyDNA( DNA )
    print( newDNA )

    # remove symbols on each side of the markers
    newDNA = trimDNA( DNA )
    print( newDNA )

def challenge4():
    sentence = "the quick red fox jumped" # input( "Sentence? " )
    print( "Sentence =", sentence )
    sum = 0
    words = sentence.split()
    for word in words:
        sum = sum + len( word )
    print( "average word length = {0:1.2f}".format( sum/len(words) ) )

def challenge5():
     students = ["Brown,Sarah", "McCharles,Charlie", "Hudson,Stanley", 
                "Smith,Margaret", "Brown,Ben", "Yang,Debbie"]
     
     # display the students
     for i in range( len( students ) ):
         print( i, students[i] )

     # get index from user
     index = 3 # input( "Which student? " )
     name = students[index]
     last, first = name.split( ',' )
     account = first[0] + last
     account = account.lower()
     print( name, account )

def main():
     newStickFigure()
     stickFigure1()
     snowMan()
     singHappy()
     singHappy2()
     DNAProblem()
     challenge4()
     challenge5()
     
main()

</showafterdate>