CSC111 Lab 9 2011

From dftwiki3
Revision as of 12:44, 2 November 2011 by Thiebaut (talk | contribs) (Multiple Boxes)
Jump to: navigation, search

--D. Thiebaut 13:15, 2 November 2011 (EDT)


Working with Functions

  • For this part, work in Idle or emacs and create the various functions this lab presents you, and test them in main().
  • For example, if you are asked to write a function that receives a string as parameter and prints it with a box around it, you could write something like this:



def boxIt( string ):
    noChars = len( s )
    print( "-" * ( 2 + noChars  + 2 ) )
    print( "| " + string + " |" )
    print( "-" * ( 2 + noChars + 2 ) )

def main():
    boxIt( "hello!" )
    boxIt( "This is a very long string!" )
    boxIt( "" ) # empty string 

main()



  • No need to add documentation for the code in this lab (or just in spots where you think you need to add markers for yourself)

Box

  • Go ahead and create the boxIt() function above.
  • Test it. Notice that I tested it with 3 different strings, one of them the empty string. It is important to test for "strange" conditions. An empty string is a totally valid string, and if our program is supposed to work with strings, it should work with empty strings as well without crashing.

Triple Boxes

  • Add a new function called BoxIt3( s1, s2, s3), that receives 3 strings and prints each string in its own box.
  • If you call your function in main() like this BoxIt3( "Hello", "There", "Smith College" ), it will print
---------
| Hello |
---------

---------
| There |
---------

-----------------
| Smith College |
-----------------

  • Go ahead and test your new function. Test it with different strings.
  • If your solution does not use the function BoxIt() created earlier, modify BoxIt3() so that it calls BoxIt() 3 times.

Multiple Boxes

  • Add a new function called multipleBoxes( L ) that receives a list of strings and prints each string in the list with BoxIt().


  • Here is are different possible ways one could test your function:


multipleBoxes( [ "Doc", "Grumpy",  "Happy", "Sleepy", "Bashful", "Sneezy", "Dopey" ] )

multipleBoxes( [ "Hello", "", "", "There!" ] )

multipleBoxes( "Hello Smith College!" . split() )





Median of 3

  • write a function that returns the median of 3 numbers.


def median3( a, b, c ):
    # could it be b?
    if a <= b and b <= c:
          return b

    # if we're here, it's not b.  Could it be a?
    if b <= a and a <= c:
          return a

    # if we're here it's not b and not a.  It has to be c!
    return c


def main():
     print( median3( 10, 10, 20 ) )
     print( median3( 1, 2, 3 )
     print( median3( 6, 5, 7 )
     print( median3( 8, 10, 9 )