Difference between revisions of "CSC111 Lab 8 2015"

From dftwiki3
Jump to: navigation, search
Line 304: Line 304:
 
I win!
 
I win!
 
Human: 0
 
Human: 0
Computer: 2
+
Computer: 3
  
 
</source>
 
</source>

Revision as of 15:06, 22 March 2015

--D. Thiebaut (talk) 14:10, 22 March 2015 (EDT)


<showafterdate after="20150325" before="20150601">

Preamble


For this lab you will write a long program called lab8.py that will

  1. include all the functions that are the solutions to the various exercises.
  2. contain one main() function that will call and test all your functions.
  3. have the following code at the end where you will call main():


if __name__=="__main__":
    main()


Part 1: While Loops


Exercise 1: Robust Input with While Loops

QuestionMark1.jpg


def getPositiveNumber():
    #
    # put your code here
    #
    return 10   # just to make sure the code is accepted by Idle


def main():

    # Part 1, Exercise 1
    x = getPositiveNumber()
    print( "getPositiveNumber() returned", x )

if __name__=="__main__":
    main()


Complete the function getPositiveNumber() so that it asks the user for a number larger than 0, and keeps on prompting the user as long as she doesn't enter a valid number.

Below is an example of the interaction between computer and user.

Please enter a number greater than 0: -1
-1 is invalid.
Please enter a number greater than 0: -3
-3 is invalid.
Please enter a number greater than 0: 0
0 is invalid.
Please enter a number greater than 0: 20
getPositiveNumber() returned 20
>>>



Exercise 2: Ask for Yes/No answer

QuestionMark2.jpg



Same idea as in Exercise 1, but this time the new function, called getYesNo() will keep on asking a question until the user's input is "YES", "yes", "y", "NO", "no", or "n". Any combination of lower/upper case in the spelling is accepted ("yES" is valid).

Source


def getYesNo():
    #
    # put your code here
    #
    return "Y"    # just to make sure the code works as is.
            
def main():
    # Part1, Exercise 2
    likesChoco = getYesNo()
    if likesChoco in ["YES", "Y" ]:
        print( "Me too!" )
    else:
        print( "Sorry to hear that!" )
        
if __name__=="__main__":
    main()


Example output


Do you like chocolate (Y/N)? possibly
please enter by 'Yes' or 'No'

Do you like chocolate (Y/N)? I don't know
please enter by 'Yes' or 'No'

Do you like chocolate (Y/N)? Oui
please enter by 'Yes' or 'No'

Do you like chocolate (Y/N)? y
Me too!



Exercise 3: While Loop and Reading File

QuestionMark3.jpg


# createFile: creates a text file containing a haiku followed by the line <<<END>>>
# followed by some text about the source of the haiku and the rights of use.
def createFile( fileName ):

    # open the file
    file = open( fileName, "w" )

    # write some text
    file.write("""
    An old pond!
    A frog jumps in-
    The sound of water.
    <<<END>>>
    Haikus from http://www.toyomasu.com/haiku/
    Feel free to use anything from this page as
    long as you make references and links to HAIKU
    for PEOPLE. Last updated: Jan 10th. 2001.
    Edited by Kei Grieg Toyomasu,
    kei at toyomasu dot com""" )

    # close the file
    file.close()

def readFileTillMarker( fileName ):
    #
    # add your code here
    #
    return []   # just to make sure the code compiles. 

def main():
    # Part 1, Exercise 3
    # create a sample text file for testing.  The file will contain the string <<<END>>>
    # in it.
    createFile( "lab8Demo.txt" )

    # get all the lines before but not including <<<END>>>
    lines = readFileTillMarker( "lab8Demo.txt" )

    # display the lines returned.  We strip them to remove the extra \n at the end and
    # the extra spaces at the front of each line.
    print( "Lines found by readFileTillMarker(): " )
    for line in lines:
        print( line.strip() )
        
if __name__=="__main__":
    main()


Same idea as the previous 2 exercises. This time you need to add code to the function readFileTillMarker() so that it will read all the lines contained in the file whose name is passed as a parameter, and that appear before the marker string <<<END>>>. In other words, the function reads the lines, adds them to a list of lines, until it finds a line containing the string <<<END>>>. It returns a list of all the lines read.

The function createFile() creates a simple file you can use for testing. Take a look at it to make sure you understand the format of the data.

Here's an example of how your program should work.


Lines found by readFileTillMarker(): 

An old pond!
A frog jumps in-
The sound of water.



Exercise 4: A bit of mathematics

QuestionMark4.jpg


Pi can be computed by adding the following terms (http://en.wikipedia.org/wiki/Pi):

Pi expansion.png


Below is a program that loops 10 times and add up the terms of the series. The program shows how the variable sum, where we accumulate the terms, gets closer and closer to PI as the loop progresses.

def computePi():
    sum = 0
    multiplier = 1
    
    for i in range( 1, 20, 2 ):
        sum = sum + multiplier * 4.0 / i
        multiplier = -multiplier
        print( "Pi = ", sum )

Modify this program so that it stops when the first 3 digits of sum are equal to 3.14. It is not acceptable to run a large number of iterations to figure out how many are necessary and change the limit of the for-loop to make it stop at the right place. Instead, your solution should use a while loop, which will stop when the sum is a number of the form 3.14xxxxxxx. Make your modified function print only the last value of sum, not all the different values it takes.




Part 2: Playing Rock-Paper-Scissors


Playing Rock, Paper, Scissors With the Computer


RockPaperScissors.jpg

Create a program called Lab8RPS.py, and start with the code shown below. Run it to see how it operates.


# lab8RPS.py
# D. Thiebaut

# define constants for indicating the winner of a round
HUMAN    = "H"
COMPUTER = "C"
TIE      = "T"

# playRound: asks the user for her play, and compares it
# to the play picked by the computer.  Returns HUMAN if
# the user wins, COMPUTER if the user loses, or TIE if
# it's a tie.
def playRound():
    human    = input( "\nYour play (R, P, or S)? " ).upper()
    computer = "R"
    return COMPUTER


# main program.  Allows the user to play against the computer,
# and reports on the winner of each rounds.
def main():
    # play rounds
    while True:
        # play one round between computer and human
        winner = playRound()

        # see if human wins
        if winner == HUMAN:
            print( "You win!" )

        # or if the computer wins
        elif winner == COMPUTER:
            print( "I win!" )
            
        # otherwise it's a tie
        else:
            print( "It's a tie!" )

if __name__=="__main__":
    main()


You will notice that this program is not fair at all. That's ok for right now. If you need the rules for this game, check this URL: http://en.wikipedia.org/wiki/Rock-paper-scissors.





Challenge #1: Keeping track of the wins

QuestionMark5.jpg


  • Modify your program and add two counters that will keep track of how many times the user or the computer win.
  • Make your program output these two counters after every round.
  • Example:


Your play (R, P, or S)? R
I win!
Human: 0
Computer: 1

Your play (R, P, or S)? S
I win!
Human: 0
Computer: 2

Your play (R, P, or S)? P
I win!
Human: 0
Computer: 3


  • Modify the program so that the function playRound() will return HUMAN instead of COMPUTER. Verify that your other counter works.
  • Same exercise, make playRound() return TIE, and verify that the two counters do not change.



Challenge #2: Computer Picks Random Shape

QuestionMark6.jpg


  • Try this code section in the Python Console.


>>> from random import choice
>>> options = [ "fruit", "dog", "farm", 3.14159, "blue" ]
>>> choice( options )
>>> choice( options )
>>> choice( options )
>>> choice( options )


  • We have seen the choice() function of the random library before. Once you have remembered how it works, add some code to playRound() so that the computer picks randomly between Rock, Paper, and Scissors.




Challenge #3: Adding some Robustness

QuestionMark7.jpg


Try running your program and entering characters that are not 'R', 'P', or 'S'. The program gets confused.
Adapt one of your solution functions of Part 1 to force your program to keep asking the user for a letter until it is valid, i.e. 'R', 'P', or 'S'.





Challenge #5: Keeping scores (Optional)

QuestionMark5.jpg


Modify your program from Challenge 3 and make it keep tack of the score. At the end of the 3 rounds the program will announce who won the 3 rounds.

This is tricky. Try to figure it out on your own and don't give up for 5 minutes. Try hard. If after that long you still can't figure it out, ask the TAs or your instructor for hints...

</showafterdate>