Difference between revisions of "CSC111 Lab 8 2015"

From dftwiki3
Jump to: navigation, search
 
(One intermediate revision by the same user not shown)
Line 2: Line 2:
 
----
 
----
  
<onlydft>
+
 
 
<tanbox>
 
<tanbox>
(box visible only if you're logged in.<br />
+
The submission page for this lab is here: [http://tinyurl.com/CSC111Lab8Submit http://tinyurl.com/CSC111Lab8Submit]
The submission page is here: [http://tinyurl.com/CSC111Lab8Submit http://tinyurl.com/CSC111Lab8Submit]
 
 
<br />
 
<br />
 
The long URL is [http://cs.smith.edu/dftwiki/index.php?title=CSC111_Lab_8_Submission_2015  http://cs.smith.edu/dftwiki/index.php?title=CSC111_Lab_8_Submission_2015].
 
The long URL is [http://cs.smith.edu/dftwiki/index.php?title=CSC111_Lab_8_Submission_2015  http://cs.smith.edu/dftwiki/index.php?title=CSC111_Lab_8_Submission_2015].
<tanbox>
+
</tanbox>
</onlydft>
 
  
 +
<br />
 
<showafterdate after="20150325 11:00" before="20150601 00:00">
 
<showafterdate after="20150325 11:00" before="20150601 00:00">
 
<br />
 
<br />

Latest revision as of 06:52, 27 March 2015

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



The submission page for this lab is here: http://tinyurl.com/CSC111Lab8Submit
The long URL is http://cs.smith.edu/dftwiki/index.php?title=CSC111_Lab_8_Submission_2015.


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

Work out all the problems of this lab, and when you are done demonstrate your working program to the lab instructor or a TA. Upon verification that your programs work well, you will be given a URL explaining what your have to submit on Moodle for this lab. The deadline for submitting on Moodle is Friday 11:00 a.m., just before class.



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()


Remove the return 10 statement in getPositiveNumber(), and complete the function 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 likesChoco() 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). The function will return True if the user answers yes, and False otherwise.

Source


def likesChoco():
    #
    # put your code here
    #
    return True    # just to make sure the code works as is.
            
def main():
    # Part1, Exercise 2
    if likesChoco() == True:
        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
HUMANWINS    = 1
COMPUTERWINS = 2
TIE          = 3

# 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 COMPUTERWINS


# 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 == HUMANWINS:
            print( "You win!" )

        # or if the computer wins
        elif winner == COMPUTERWINS:
            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() returns 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: Figuring out who wins

QuestionMark6.jpg


  • This is probably the most challenging part of this program.
  • Given the user's play ('R', 'S', or 'P') and the computer's play (one of the same 3 letters), you need to make the program decide who wins or if there's a tie.
  • Because your program currently picks a play that is fixed, it will be time-consuming to test your code with all possible combinations of user and computer plays, and verify that it works in all cases.
  • A much better alternative is to create another program, very short, that can run through all possible cases for you, and allow you to verify whether you have the right logic for deciding the winner.
  • Create a new program, called testRPSAlgorithm.py with the code below:


# testRPSWinner.py
# D. Thiebaut
# This program tests all the possible combinations
# of user and computer plays in the game of rock
# paper, scissors.
# Rules:
# user  computer winner
#   R      R       Tie
#   R      P       C
#   R      S       H
#   P      R       H
#   P      P       Tie
#   P      S       C
#   S      R       C
#   S      P       H
#   S      S       Tie

HUMANWINS    = 1
COMPUTERWINS = 2
TIE          = 3

def winner( user, computer ):
    if user=='R' and computer=='R':
        return HUMANWINS
    else:
        return COMPUTERWINS
    

print( "user computer winner" )
for user in [ 'R', 'P', 'S' ]:
    for computer in [ 'R', 'P', 'S' ]:
        win = winner( user, computer )
        if win == HUMANWINS:
            win = "human"
        elif win == COMPUTERWINS:
            win = "computer"
        else:
            win = "tie"
        print( "#  ", user, "    ", computer, "     ", winner( user, computer ) )


  • Run the program. Notice that it lists all the possible combinations for a play by the user and by the computer. The outcome, though, is not correct.
  • Modify the code in the winner() function so that it returns the correct output in all cases.
  • There are many different ways to solve this... Don't worry about efficiency too much. Concentrate on having something that works correctly. Note that there are 3 cases when the user wins, 3 cases for which the computer wins, and 3 cases when we have a tie.
  • Once you have the correct behavior for your winner() function, copy/paste it into your Lab8RPS.py program. Make playRound() use this function to figure out what to return to the main program.



Challenge #3: Computer Picks Random Character

QuestionMark9.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.
  • Run your program, and verify that it shows what the computer picks, and who wins the round.




Challenge #4: 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 and add a new function to your program called getUserInput(), that will prompt the user for a letter, and will keep prompting her until the letter entered is either 'R', 'P', or 'S'. Make playRound() use this function to get the user's play.
  • Test your program well. Enter letters that are not valid and verify that your program keeps prompting for a new input every time.



Challenge #5: Keeping scores

QuestionMark5.jpg


Modify your program so that it will allow the user to play only 3 rounds against the computer, and then stop, announcing who the winner is.



Challenge #6: Keeping Playing until Difference between Scores is 3

QuestionMark8.jpg


  • This is a bit trickier. Modify your program so that it will let the user play against the computer as long as the difference between the two scores is less than 3. When the difference is equal to 3, then the program stops and displays the winner.

</showafterdate>

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

Solution Programs


Part 1


# Lab8sol.py
# D. Thiebaut


def getPositiveNumber():
    while True:
        x = int( input( "Please enter a number greater than 0: " ) )
        if x > 0:
            return x
        print( x, "is invalid." )


def likesChoco():
    # list all allowed valid answers
    validAns = ['y','yes','n','no']

    # seed the loop
    x = ""
    while x in validAns == False:
        x = input("Do you like chocolate (y/n)? ")
        x = x.lower()

    if x in ['y', 'yes']:
        return True
    else:
        return False

def createFile( fileName ):
    file = open( fileName, "w" )
    file.write("""
    Haikus from http://www.toyomasu.com/haiku/
    An old pond!
    A frog jumps in-
    The sound of water.
    <<<END>>>
    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""" )
    file.close()

def readFileTillMarker( fileName ):
    file = open( fileName, "r" )
    lines = []
    for line in file:
        if line.find( "<<<END>>>" ) != -1:
            return lines
        else:
            lines.append( line )
    return lines

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

def computePi2():
    sum = 0
    multiplier = 1

    i = 1
    while ( not ( 3.14 <= sum < 3.15 ) ):
        sum = sum + multiplier * 4.0 / i
        i = i+2
        multiplier = -multiplier
        print( "Pi = ", sum )
    print( "Final version of Pi = ", sum )
        
def main():

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

    # Part 1, Exercise 2
    if likesChoco() == True:
        print( "Me too!" )
    else:
        print( "Sorry to hear that!" )

    # Part 1, Exercise 3
    createFile( "lab8Demo.txt" )
    lines = readFileTillMarker( "lab8Demo.txt" )
    print( "Lines found by readFileTillMarker(): " )
    for line in lines:
        print( line.strip() )

    # Part 1, Exercise 4
    computePi2()
    
if __name__=="__main__":
    main()


Part 2


# lab8RPS_solution.py
# D. Thiebaut

from random import choice

# define constants for indicating the winner of a round
HUMANWINS    = 1
COMPUTERWINS = 2
TIE          = 3


# getUserInput(): prompts the user for a letter that is
# either 'R', 'S' or 'P'.  Keeps prompting until input is
# correct.
def getUserInput():
    while True:
        ans = input( "\n\nYour play (R, S, P)? " ).upper()
        if ans in ['R', 'S', 'P']:
            return ans
        print( "invalid input.\n" )
        
# winner(): decides who the winner is from the two characters
# passed, representing the user's and the computer's play.
def winner( user, computer ):
    # create a string with the 2 letters
    userComputer = user + computer

    # test two-letters and combinations of user winning
    if userComputer in [ "RS", "PR", "SP" ]:
        return HUMANWINS

    # test two-letters and combinations of ties
    if userComputer in [ "RR", "PP", "SS" ]: 
        return TIE

    # if we haven't returned yet, then the computer wins
    return COMPUTERWINS



# 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    = getUserInput()
    computer = choice( ['R', 'P', 'S'] )
    win = winner( human, computer )
    print( "human:", human, "  computer:", computer )
    return win


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

        # see if human wins
        if winner == HUMANWINS:
            hCount += 1
            print( "You win!  Scores: computer:", cCount, " you:", hCount )

        # or if the computer wins
        elif winner == COMPUTERWINS:
            cCount += 1
            print( "I win!  Scores: computer:", cCount, " you:", hCount )
            
        # otherwise it's a tie
        else:
            print( "It's a tie!  Scores: computer:", cCount, " you:", hCount )

        if abs( cCount - hCount ) >= 3:
            break

    # announce the winner of the game
    if cCount > hCount:
        print( "\nYou lost the game!" )
    else:
        print( "\nCongrats, you won this, fair and square!" )


if __name__=="__main__":
    main()


</showafterdate>



...